简体   繁体   English

该程序计算二维int数组的最小值

[英]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. 程序将显示:[1,2,4]-每个尺寸的最小值。 For that I've created a method called minimum, which looks like this 为此,我创建了一个名为minimum的方法,如下所示

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,]. 程序显示[0,0,0,]。 Do You have any clue where is the problem and how to fix it? 您是否有问题的根源以及如何解决?

The problem is that if the first element in the array is min, it never gets recorded to the result array. 问题在于,如果数组中的第一个元素为min,则永远不会将其记录到结果数组中。 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. 添加条件或使用Integer.MIN_VALUE处理空行。

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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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