[英]Number of times a value occurs in each column of a 2d-array in Java?
ArrayList<Integer> newArray = new ArrayList<>();
for (int i =0; i < count; i++) {
newArray.add(i);
}
for (int j = 0; j <= 3; j++) {
Collections.shuffle(newArray);
System.out.println(newArray.toString());
}
//Let count equal 4 since we want a square
int[][] counters = new int[count][count];
int numAppear = 0;
int row = 0;
int col = 0;
for (row = 0; row < count; row++) {
for (col = 0; col < count; col++) {
if (newArray.get(row).equals(newArray.get(col))) {
numAppear++;
}
counters[row][col] = numAppear;
System.out.print(counters[row][col]+" ");
}
System.out.println();
}
In the code, I want to find how many times if i visit column j of row i, i appears at index j in the ArrayList for all the shuffles. 在代码中,我想查找如果我访问第i行的第j列有多少次,那么我会在ArrayList的索引j中出现所有的随机播放。
Also, I'm trying to print counter array, but i get memory hashes although i tried .toString as well as Arrays.toString 另外,我正在尝试打印计数器数组,但是尽管尝试了.toString以及Arrays.toString,但我得到了内存哈希。
Let's say this is my output for shuffled array: 假设这是我对混洗数组的输出:
[3, 1, 2, 0]
[2, 0, 1, 3]
[1, 3, 2, 0]
[0, 1, 2, 3]
Now output for counters[row][col] = numAppear; 现在输出counters [row] [col] = numAppear; should look like this: First row:since row0 = col0 of shuffled array, numAppear = 1.
应该看起来像这样:第一行:因为row0 =改组数组的col0,numAppear = 1。
Third row there's a 2 in (2,2) because in (2,2) of shuffled array, #2 appears twice in the same column but in the previous rows 第三行在(2,2)中有一个2,因为在(2,2)的随机数组中,#2在同一列中出现两次,但在前几行中
[1, 1, 1, 1]
[1, 1, 1, 1]
[1, 1, 2, 2]
[1, 2, 3, 2]
Why are you using 'counters[row][col] = numAppear;' 为什么使用“ counters [row] [col] = numAppear;” ?
?
If it's just to eventually count it, initialize another int counter before you start iterating through the elements. 如果只是为了最终计数,请在开始遍历元素之前初始化另一个int计数器。
Since "numAppear" value persists between matches, I don't see the value in adding the temporary "numAppear" value to an array. 由于“ numAppear”值在两次匹配之间仍然存在,因此在将临时 “ numAppear”值添加到数组时看不到该值。 If I understand the goal of your print statement, this might be a viable alternative:
如果我了解您的打印声明的目标,那么这可能是一个可行的选择:
System.out.println("Found a match at row " + row + " and column " + col); System.out.println(“在“ +行+”行和“ + col列”找到匹配项;
Edit: As for printing the matches, I'd initialize an array list at the outset and iterate through it at the end. 编辑:至于打印比赛,我从一开始就初始化了一个数组列表,并在最后进行遍历。 eg:
例如:
ArrayList<String> matchList = new ArrayList<String>();
To add to it: 要添加到它:
matchList.add(numAppear);//or whatever you're trying to add
Then at the end: 然后最后:
for (String s : matchList){
System.out.println("Match at: " + s);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.