[英]How do i get minimum sum of 2D Array in Java?
I have this code, which calculates the sum of all rows in 2D array but I want to print the smallest sum of rows also.我有这段代码,它计算二维数组中所有行的总和,但我也想打印最小的行总和。
Here down is my code:下面是我的代码:
package com.example;
import java.util.Arrays;
public class discrete2 {
public static void main(String[] args) {
int a[][] = {
{0, 1, 1, 0, 1, 0, 0, 1, 0},
{1, 0, 1, 1, 0, 0, 0, 1, 0},
{1, 0, 0, 1, 0, 1, 1, 0, 1},
{0, 1, 0, 0, 0, 1, 0, 0, 1},
{0, 0, 1, 1, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 1, 1, 0},
{0, 0, 0, 0, 1, 1, 1, 0, 0}
};
int rows = a.length;
int cols = a[0].length;
int sumCol;
for(int i = 0; i < cols; i++){
sumCol = 0;
for(int j = 0; j < rows; j++){
sumCol = sumCol + a[j][i];
}
System.out.println("Sum of " + (i+1) +" column: " + sumCol);
}
}
}
I tried to changing my code to have variable that remembers the smallest number but it's not working somehow and gives out 3, when it should be 2.我试图改变我的代码,让变量记住最小的数字,但它以某种方式不起作用,并在它应该是 2 的时候给出了 3。
public static void main(String[] args) {
int a[][] = {
{0, 1, 1, 0, 1, 0, 0, 1, 0},
{1, 0, 1, 1, 0, 0, 0, 1, 0},
{1, 0, 0, 1, 0, 1, 1, 0, 1},
{0, 1, 0, 0, 0, 1, 0, 0, 1},
{0, 0, 1, 1, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 1, 1, 0},
{0, 0, 0, 0, 1, 1, 1, 0, 0}
};
int rows = a.length;
int cols = a[0].length;
int sumCol;
int minSumCol = 100000000; // arbitrary large value
for (int i = 0; i < cols; i++) {
sumCol = 0;
for (int j = 0; j < rows; j++) {
sumCol = sumCol + a[j][i];
}
minSumCol = Math.min(minSumCol, sumCol);
System.out.println("Sum of " + (i + 1) + " column: " + sumCol);
}
System.out.println("Min sum in the matrix is: " + minSumCol);
}
Hi, your code is indeed correct.您好,您的代码确实是正确的。 It does return 2 as the smallest value.
它确实返回 2 作为最小值。 This is the output that I got:
这是我得到的 output:
Sum of 1 column: 3 1 列的总和:3
Sum of 2 column: 2 2列的总和:2
Sum of 3 column: 3 3列总和:3
Sum of 4 column: 3 4列总和:3
Sum of 5 column: 2 5列总和:2
Sum of 6 column: 3 6 列总和:3
Sum of 7 column: 3 7 列总和:3
Sum of 8 column: 3 8 列总和:3
Sum of 9 column: 3 9 列总和:3
Min sum in the matrix is: 2矩阵中的最小和为:2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.