2014-03-02 44 views
0

我想檢查一個重複項是否存在於一個2D數組的行中並將其替換。檢查在java行中只有一個2d數組中的重複項

因此,如果數組是:

7, 5, 6, 1, 7, 5, 7, 1 // would change the 7 in [4] and [6] 
2, 4, 3, -1, 7, 5, 8, 3 // would change the 3 in [7] 
8, 7, 2, -3, 7, 1, 5, 1 
5, 7, 3, 2, 4, 5, -4, 8 
6, 1, 8, 2, 2, 6, 1, 3 

int row = 0; 
if (row < zipcodelist.length) { 
    for (int z = 0; z < zipcodelist[row].length; z++) { 
     for (int y = 1; y < zipcodelist[row].length; y++) { 
      if (zipcodelist[row][z] == zipcodelist[row][y]) { 
       zipcodelist[row][y] = 1 + generator2.nextInt(8); 
      } else if (zipcodelist[row][z] != zipcodelist[row][y]) { 
       System.out.println("Not duplicate"); 
      } 
     } 
    } 
    row++; 
} 

但有了這個代碼,一切都在變化,而不僅僅是重複。我究竟做錯了什麼?

+0

對不起,這個generator2.nextInt是要生成一個隨機數,這樣做的代碼是: Random generator2 = new Random(); – user3369920

+0

我不明白你想要什麼 –

回答

1

你應該在第二次迭代的行不在列表中的第二個元素

所以

for(int y = 1; y<zipcodelist[row].length; y++){ 

for(int y = z + 1; y<zipcodelist[row].length; y++){ 

希望更換這有助於在未來的元素開始。

1

作爲替代方案,您可以使用HashSet。你當前的嵌套循環是O(n^2)。

int [] array = {7,5,6,1,7,5,7,1}; 

Set alreadyExamined = new HashSet(); 

for(int i=0; i<array.length; i++){ 
    if(alreadyExamined.contains(array[i])){ 
     array[i] = new Random().nextInt(8)+1; 
    } 
    else{ 
     alreadyExamined.add(array[i]); 
    } 
} 

注意:如果你的目標是消除重複,那麼它有可能是新生成的號碼是前一個數字的另一個副本。

0

但在這裏,如果你刪除了類似於跟第一次迭代中重複,

7,5,6,1,,5,7,1

7,5,6,1,,5,5 ,1

然後在下一次迭代可以製成再次重複類似的後續,

7,,6,1,6,5,5,1

7,,6,1,6,,,1

以便我認爲這種類型的隨機號碼發生器不適合這個。

+0

什麼是更好的選擇? – user3369920