2015-05-29 102 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()]);' 。现在都很好。 –