简体   繁体   English

Java 二维数组(矩阵)。 每行的总和分别

[英]Java 2D array (matrix). Sum of each row separately

I know how to scan how to print matrix.我知道如何扫描如何打印矩阵。 Also I know how to get sum of each row.我也知道如何得到每一行的总和。

I have a task to scan matrix, then to calculate sum of each row separately, and then to make new matrix and to exclude a row with the smallest sum.我的任务是扫描矩阵,然后分别计算每一行的总和,然后制作新矩阵并排除总和最小的行。

Try this.尝试这个。

public static void main(String[] args) {
    int[][] matrix = {
        {0, 1, 2},
        {3, 4, 5},
        {6, 7, 8}};

    int minRowSum = Stream.of(matrix)
        .mapToInt(row -> IntStream.of(row).sum())
        .min().getAsInt();
    
    int[][] result = Stream.of(matrix)
        .filter(row -> IntStream.of(row).sum() > minRowSum)
        .toArray(int[][]::new);

    for (int[] row : result)
        System.out.println(Arrays.toString(row));
}

output: output:

[3, 4, 5]
[6, 7, 8]

If only the first row with minimal sum needs to be deleted, it may be needed to find the index of the minimal row.如果只需要删除总和最小的第一行,则可能需要找到最小行的索引。

Also, the row sums are not calculated here in the second pass.此外,在第二遍中不计算行总和。

public static int[][] removeMinRow(int[][] data) {
    int indexOfMinRow = IntStream.range(0, data.length)
        .boxed()
        .min(Comparator.comparingInt(i -> Arrays.stream(data[i]).sum()))
        .orElse(-1);
    
    if (indexOfMinRow == -1) {
        return data; // nothing to delete from
    }

    int[][] result = new int[data.length - 1][];
    for (int i = 0, j = 0; i < data.length; i++) {
        if (i != indexOfMinRow) {
            result[j++] = data[i]; // reassigning references to rows
        }
    }
    
    return result;
}

Test:测试:

int[][] data = {
    {3, 4, 5},
    {0, 2, 1},           
    {6, 7, 8},
    {0, 1, 2},
};

System.out.println(Arrays.deepToString(removeMinRow(data)));

Output (only the row at index 1 get deleted): Output(仅删除索引 1 处的行):

[[3, 4, 5], [6, 7, 8], [0, 1, 2]]

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

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