繁体   English   中英

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

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

我知道如何扫描如何打印矩阵。 我也知道如何得到每一行的总和。

我的任务是扫描矩阵,然后分别计算每一行的总和,然后制作新矩阵并排除总和最小的行。

尝试这个。

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:

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

如果只需要删除总和最小的第一行,则可能需要找到最小行的索引。

此外,在第二遍中不计算行总和。

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

测试:

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

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

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