[英]How do i find and count duplicates in a 2 dimensional array?
嗨,我正在嘗試通過一個二維數組(特別是一個4x4數組),並找到任何重復的數字,然后計算數字重復的次數。 到目前為止,我有4個for循環可行但是做的比我真正想要的更多。
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< dataTable.length; a++)
{
if ( x != z && x !=a && y != z && y !=a)
{
if (dataTable[x][y] == dataTable[z][a])
{
counter1++;
}
}
}
}
if (counter1 > 1)
{
huh += ("\n " + dataTable[x][y] + " repeats " + counter1 + " times!");
}
counter1=1;
}
}
基本上這是有效的,它將我的數組中的每個數字與包括其自身在內的每個其他數字進行比較(但是if語句使它不能自我計數)。 基本上我需要輸出來表示簡單的東西
The number 3 repeats 3 times
但是,通過我的設置工作方式,每次比較數組中每個位置的數字3時,它會向字符串添加相同的語句。 那么我的方法是否正確,只需要一些調整? 或者完全錯了,我需要一些完全不同的東西? 我只是在我大學的初學者編程課程中,所以我們到目前為止只知道java的基礎知識,如數組,循環和其他一些東西。
我認為最好的方法是維護一個Map<Integer, Integer>
來跟蹤數字頻率(即它將數組中的每個數字映射到它出現的次數)。 循環遍歷整個數組並相應地更新此映射並不困難。 你現在正在做的方式似乎比它更復雜真正需要(在我看來)。
你為什么要使用4個 for-loops? 也許我誤解了你的特定代碼的目的,但你應該只需要兩個循環2D數組(並最終計算數字頻率):
for (int[] a : array)
for (int i : a)
// do something
相關文件:
只需將此數組轉換為Map<Integer, Integer>
,然后將其打印出來,如下所示:
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<Integer, Integer> map = new HashMap<Integer, Integer> ();
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<Integer, Integer> entry : map.entrySet()) {
System.out.println(String.format ("The number %d repeats %d times", entry.getKey(), entry.getValue()));
}
}
在這里你可以找到結果。
最普遍的解決方案是使用地圖,正如其他人所建議的那樣。 但是,如果數組值在相對較小的范圍內,則可以使用數組而不是地圖。 如果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]++;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.