如何在二维数组中查找和计算重复项?
嗨我正在尝试通过一个二维数组(特别是一个4×4数组),并找到任何重复的数字,然后计算数字重复的次数。 到目前为止,我有4个循环工作,但是做的比我真正想要的更多。
int counter1 =1; String huh=""; for (int x = 0; x< dataTable.length; x++) { for (int y=0; y< dataTable.length; y++) { for (int z = 0; z< dataTable.length; z++) { for (int a=0; a 1) { huh += ("\n " + dataTable[x][y] + " repeats " + counter1 + " times!"); } counter1=1; } }
基本上这是有效的,它将我的数组中的每个数字与包括其自身在内的每个其他数字进行比较(但是if语句使它不能自我计数)。 基本上我需要输出来表示简单的东西
The number 3 repeats 3 times
但是,对于我的设置工作方式,它会在每次比较数组中每个位置的数字3时向字符串添加相同的语句。 那么我的方法是否正确,只需要一些调整? 或者完全错了,我需要一些完全不同的东西? 我只是在我大学的初学者编程课程中,所以我们只知道java的基础知识,如数组,循环和其他一些东西。
只需将此数组转换为Map
,然后将其打印出来,如下所示:
public static void main(String[] args) throws Exception { final int[][] dataTable = new int[][] { new int[] {0, 1, 2, 1}, new int[] {0, 1, 3, 1}, new int[] {0, 1, 2, 2}, new int[] {0, 1, 2, 0} }; final Map map = new HashMap (); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { final int value = dataTable[i][j]; final Integer currentCount = map.get(value); final Integer newCount; if (currentCount == null) { newCount = 1; } else { newCount = currentCount + 1; } map.put (value, newCount); } } for (final Map.Entry entry : map.entrySet()) { System.out.println(String.format ("The number %d repeats %d times", entry.getKey(), entry.getValue())); } }
在这里你可以找到结果。
我认为最好的方法是维护一个Map
来跟踪数字频率(即它将数组中的每个数字映射到它出现的次数)。 循环遍历整个数组并相应地更新此映射并不困难。 你现在正在做的事情似乎比它真正需要的更复杂(在我看来)。
你为什么要使用4个 for循环? 也许我误解了你的特定代码的目的,但你应该只需要两个循环2D数组(并最终计算数字频率):
for (int[] a : array) for (int i : a) // do something
相关文件:
-
Map
最普遍的解决方案是使用地图,正如其他人所建议的那样。 但是,如果数组值在相对较小的范围内,则可以使用数组而不是地图。 如果min
是(最多)数组中的最小值, max
是(至少)最大值:
public int[] getFrequencyMap(int[][] array, int min, int max) { int[] map = new int[max - min + 1]; for (int[] row : array) { for (int val : row) { map[val - min]++; } } return map; }
在返回的数组中,索引val - min
处的值将是值val
在数组中出现的次数。
你可以有一个n * n行和2列的数组:
/*being n the number of rows/columns*/ int count[]][] = new int[n*n][2]; for (int i = 0; i < dataTable.length; i++) { for (int k = 0; k < dataTable.length; k++) { /*this loop finds the position in which it should go*/ for (int h = 0; h < n*n; h++) { if (count[h][0] == dataTable[i][k]) { break; } /*Assuming that '0' is not a possible number in dataTable, use '-1' or a number that */ if (count[h][0] == 0) { break; } } count[h][0] = dataTable[i][k]; count[h][1]++; } }