简体   繁体   中英

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.

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. This is the output that I got:

Sum of 1 column: 3

Sum of 2 column: 2

Sum of 3 column: 3

Sum of 4 column: 3

Sum of 5 column: 2

Sum of 6 column: 3

Sum of 7 column: 3

Sum of 8 column: 3

Sum of 9 column: 3

Min sum in the matrix is: 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM