Bruno
Bruno

Reputation: 92

Program which counts minimum of a two dimensional int array

I am trying to create a program, which counts the minimum of each dimension in a two dimensional array. So for ex. if i had an array:

int[][] test = {{1,2,3},{2,3,4},{4,5,6}}

the program would display: [1,2,4] - the minimum of each dimension. For that I've created a method called minimum, which looks like this

static int[] minimum(int[][] arr) {
        int[] result = new int [arr.length];
        for (int i = 0; i < arr.length; i++) {
            for(int j = 0; j < arr[i].length; j++) {
                int  min = arr[i][0];
                if(arr[i][j] < min) {
                    min = arr [i][j];
                    result [i] = min;
                } else{

                }
            }
        }
        return result;
    }

But when i call out this method in my main, with a sample array

public static void main(String[] args) {
            int[][] arr = {{1,2,3,},{3,4,5},{6,6,6}};
        System.out.println(Arrays.toString(minimum(arr)));


    }

The program displays [0,0,0,]. Do You have any clue where is the problem and how to fix it?

Upvotes: 2

Views: 71

Answers (2)

ggorlen
ggorlen

Reputation: 57344

The problem is that if the first element in the array is min, it never gets recorded to the result array. Try:

static int[] minimum(int[][] arr) {
    int[] result = new int[arr.length];

    for (int i = 0; i < arr.length; i++) {
        result[i] = arr[i][0];

        for (int j = 1; j < arr[i].length; j++) {
            if (arr[i][j] < result[i]) {
                result[i] = arr[i][j];
            }
        }
    }

    return result;
}

Note that there needs to be at least one element per row in the input matrix for the above function; add a conditional or use Integer.MIN_VALUE to handle empty rows if you wish.

Upvotes: 3

Tianhao Wang
Tianhao Wang

Reputation: 186

This should work. You reset the min to the first element every time. So you are basically comparing if there is any value smaller than the first one.

    static int[] minimum(int[][] arr){
        int[] result = new int [arr.length];
        for (int i = 0; i < arr.length; i++){
            result[i] = Integer.MAX_VALUE;
            for(int j = 0; j < arr[i].length; j++){
                if(arr[i][j] < result[i]) {         
                    result [i] = arr[i][j];
                }
            }
        }
        return result;
    }

Upvotes: 0

Related Questions