2015-05-29 141 views
5
public static String[][][] cleanUp(String[][][] array) { 
    for (int f = 0; f < array.length; f++) { 
     for (int g = 0; g < array[f].length; g++) { 
      int position = 0; 
      //boolean flag = false; 
      int count = 0; 
      for (int h = 0; h < array[f][g].length; h++) { 
       if (array[f][g][h].equals(array[f][g][h+1])) count++; 
       else { 
        ArrayList<String> temp = new ArrayList<String>(Arrays.asList(array[f][g])); 
        for (int i = count - 1; i > position; i--) { 
         temp.remove(i); 
         position = i-1 ; 
        } 
        temp.set(position, array[f][g][h] + " (" + count + ")"); 
       } 
      } 
     } 
    } 
    return array; 
} 

從本質上講,我想要做的是採取串的3D陣列並具有各自1D陣列中的它的重複值顯示數量一起相同的值。舉例來說,如果我有字符串的一個這樣的數組:合併在一個陣列

[go, go, go, go, go, go] 
[go, stop, stop, stop] 

它會成爲:

[go (5)] 
[go (1), stop (3)] 

我怎麼能做到這一點,它是什麼,我做錯了什麼?

+6

您可以通過適當比較字符串開始(使用等於,不==) – Eran

+1

據我所知,數組的2個外形尺寸是無關的重複數據刪除。如果是這樣的話,可能會更容易考慮如何爲'String []'執行此操作,然後在兩個for循環中將該方法的調用包裝爲迭代外部維度。 –

+0

@Eran呃。我修正了這個問題,但它仍然不起作用。無論哪種方式,我都會得到一個'ArrayIndexOutOfBoundsException'。 –

回答

5

你需要改變你的最後一個內部循環:

 int count = 0; 
     for (int h = 0; h < array[f][g].length; h++) { 
      if (array[f][g][h].equals(array[f][g][h+1])) count++; 
      //You dont check for out of bound here, so `h + 1` will cause out of bound error 
      else { 
       ArrayList<String> temp = new ArrayList<String>(Arrays.asList(array[f][g])); 
       for (int i = count - 1; i > position; i--) { 
        temp.remove(i); 
        position = i-1 ; 
       } 
       temp.set(position, array[f][g][h] + " (" + count + ")"); 
      } 
      //Count is not reset after this, so this will be wrong! 
     } 

我會怎麼做:

 ArrayList<String> tmp = new ArrayList<>(); 
     for (int h = 0; h < array[f][g].length; h++) { 
      int count = 1; 
      while(h + count < array[f][g].length && array[f][g][h].equals(array[f][g][h+count])) 
       count++; 
      tmp.add(array[f][g][h] + "(" + count + ")"); 
      h += count - 1;//Update h to skip identical element 
     } 

ArrayList的tmp將持有的結果爲array[f][g],你應該注意到我如何更新h因此跳過所有相同的元素。

更新:測試result

+0

嗯,沒有幫助。我仍然得到[this](https://i.imgur.com/oJdL9tn.png)。 –

+0

@CalvinKinzie對不起,我無法查看鏈接(這是我的網絡問題),但是,我測試了我的代碼,結果是[here](http://ideone.com/78VQ8u)。所以我認爲它是直接用於三維或更多維數組,你不需要再使用'position' :) –

+0

啊,謝謝。我也意識到我的錯誤是我從來沒有在你的代碼中的右括號後加上'array [f] [g] = tmp.toArray(new String [tmp.size()]);' 。現在都很好。 –