Home > front end >  Java 2D array (matrix). Sum of each row separately
Java 2D array (matrix). Sum of each row separately

Time:11-18

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.

CodePudding user response:

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:

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

CodePudding user response:

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):

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