英文:
How can i find the row which has the most 0 values in an int 2D array?
问题
如何找到具有最多0值的行在一个int二维数组中?
示例:
int[][] arr = new int[4][5];
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[0][3] = 4;
arr[1][0] = 29;
arr[1][1] = 28;
arr[1][2] = 27;
arr[2][0] = 3;
arr[2][1] = 33;
arr[3][0] = 41;
arr[3][1] = 42;
arr[3][2] = 43;
arr[3][3] = 43;
答案应该是行索引2。
英文:
How can i find the row which has the most 0 values in an int 2D array?
Example:
int[][] arr = new int[4][5];
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[0][3] = 4;
arr[1][0] = 29;
arr[1][1] = 28;
arr[1][2] = 27;
arr[2][0] = 3;
arr[2][1] = 33;
arr[3][0] = 41;
arr[3][1] = 42;
arr[3][2] = 43;
arr[3][3] = 43;
The answer is should be Row index 2
答案1
得分: 1
以下是翻译好的部分:
有几种方法可以实现你的目标。我会使用 stream
来完成这个任务:
int[][] arr = new int[4][5];
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[0][3] = 4;
arr[1][0] = 29;
arr[1][1] = 28;
arr[1][2] = 27;
arr[2][0] = 3;
arr[2][1] = 33;
arr[3][0] = 41;
arr[3][1] = 42;
arr[3][2] = 43;
arr[3][3] = 43;
IntStream.range(0, arr.length).boxed()
.map(row -> Map.entry(row, Arrays.stream(arr[row]).filter(i -> i != 0).count()))
.min(Comparator.comparing(Entry::getValue))
.map(Entry::getKey)
.ifPresent(row -> System.out.println("行: " + row));
输出
行: 2
更新
如果你想使用 for
循环,可以这样做:
int row = -1;
int maxZeros = 0;
for (int i = 0; i < arr.length; i++) {
int zeros = 0;
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 0) {
zeros++;
}
}
if (zeros > maxZeros) {
maxZeros = zeros;
row = i;
}
}
if (row > -1) {
System.out.println("行: " + row);
}
输出
行: 2
英文:
There are several ways to achieve your goal. I would use stream
s for that job:
int[][] arr = new int[4][5];
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[0][3] = 4;
arr[1][0] = 29;
arr[1][1] = 28;
arr[1][2] = 27;
arr[2][0] = 3;
arr[2][1] = 33;
arr[3][0] = 41;
arr[3][1] = 42;
arr[3][2] = 43;
arr[3][3] = 43;
IntStream.range(0, arr.length).boxed()
.map(row -> Map.entry(row, Arrays.stream(arr[row]).filter(i -> i != 0).count()))
.min(Comparator.comparing(Entry::getValue))
.map(Entry::getKey)
.ifPresent(row -> System.out.println("Row: " + row));
Output
Row: 2
Update
If you want to use a for loop
you can do:
int row = -1;
int maxZeros = 0;
for (int i = 0; i < arr.length; i++) {
int zeros = 0;
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == 0) {
zeros++;
}
}
if (zeros > maxZeros) {
maxZeros = zeros;
row = i;
}
}
if (row > -1) {
System.out.println("Row: " + row);
}
Output
Row: 2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论