2012-07-15 80 views
1

我有一個整數數組的列表,我想檢查每個數組是否按時間順序排列,如果不是,我希望它從列表中移除。檢查數組是否按時間順序排列

目前,我不喜歡這樣寫道:

for (int i = 0; i < allXcombis.Count(); i++) 
{ 
    bool remove = false; 
    for (int j = 0; j < allXcombis[i].Length; j++) 
    { 
     if (allXcombis[i].Count() - 1 > j) 
      if (allXcombis[i][j] != allXcombis[i][j + 1] - 1) 
       remove = true; 
    } 
    if (remove) 
     allXcombis.Remove(allXcombis[i]); 
} 

但我不是這個代碼真的很開心,我想這是可以做到更容易。

+4

什麼是「時間」 – 2012-07-15 09:37:12

+0

@petar:http://en.wikipedia.org/wiki/Chronological – 2012-07-15 13:07:03

回答

0

當您從列表中刪除循環內容時,您需要修復循環變量或向後循環。然後,你不需要Count()之後。分配remove = true後,您可以從循環中斷開,這將提高性能。

for (int i = allXcombis.Count - 1; i >= 0; i--) 
{ 
    bool remove = false; 
    for (int j = 0; j < allXcombis[i].Length; j++) 
    { 
     if (allXcombis[i].Length - 1 > j) 
     { 
      if (allXcombis[i][j] != allXcombis[i][j + 1] - 1) 
      { 
       remove = true; 
       break; 
      } 
     } 
    } 
    if (remove) 
     allXcombis.Remove(allXcombis[i]); 
} 
0

如果按照時間順序排序,那麼您需要檢查<而不是!=。 你也可以簡化一些事情。最重要的是,當你發現它沒有被排序以脫離內部循環,所以你不會繼續迭代。 你也需要減少我當你刪除,因爲你會跳過一些數組,否則(如果我= 2,你刪除第二個數組,然後第三個數組成爲第二,但我會在下一個迭代3,所以你會跳過它)

for (int i = 0; i < allXcombis.Count; i++) 
{ 
    for (int j = 0; j < allXcombis[i].Length-1; j++) 
    { 
     if (allXcombis[i][j] > allXcombis[i][j + 1] - 1) 
     { 
      allXcombis.Remove(allXcombis[i]); 
      i--; 
      break; 
     } 
    } 
} 
+0

如果它是List,則不需要()Count – 2012-07-15 09:57:05

2

首先,我可能會提取檢查數組是「時間」到了自己的方法,並使其更加有效,通過return從環早期荷蘭國際集團:

bool IsChronological(int[] array) 
{ 
    for (int i = 0; i < array.Length - 1; i++) 
    { 
     if (array[i] != array[i + 1] - 1) 
      return false; 
    } 

    return true; 
} 

然後我會簡單地使用RemoveAll()

allXcombis.RemoveAll(a => !IsChronological(a)); 

通過這種方式,您可以獲得簡潔易讀的代碼,而且不必擔心列表中的索引(如其他人提到的,您的代碼中存在一個錯誤,因爲您不小心索引)。

0

svick在使用專用方法的認同一樣,他提出了「IsChronological」,但我想安全性和性能的一點點添加到此方法:

bool IsChronological(int[] array) 
{ 
    bool result = ((array == null) || (array.Length == 0)) ? false : true; //Null or empty arrays are not chronological by definition (also avoid exceptions) 
    if (result) 
    { 
     result = (array.Length == 1) ? true : false; //Arrays with only one element are chronological by definition 
     if (!result) 
     { 
      int length = array.Length - 1; 
      int index = 0; 
      while ((index < length) && (array[index] == array[index] + 1)) 
       index++; 
      result = (index == array.length); 
     } 
    } 
    return result; 
}