Home > Enterprise >  How to reverse the rows of the matrix, if the sum row is less than the sum last column?
How to reverse the rows of the matrix, if the sum row is less than the sum last column?

Time:05-13

How can I reverse rows in a matrix, which sums less than the sum last column?
For example:

    1,2,3 -> sumRow1 = 6;
    4,5,6 -> sumRow2 = 15;
    7,8,9 -> sumRow3 = 24;
    sumLastCol = 18;
    row1 & row2 - reverse, row3 - unchange

Can I do it at once in the matrix or do I need to create a new array? This is my code, but it doesn't work correctly:

  public static void reverseMatrix(int n, int[][]randMatrix, int sumRow, int sumCol){
        for(int i=0; i<n; i  ){
            int start = 0;
            int end = n-1;
            if(sumRow<sumCol) {
                while (start < end) {
                    int temp = randMatrix[i][start];
                    randMatrix[i][start] = randMatrix[i][end];
                    randMatrix[i][end] = temp;
                    start  ;
                    end--;
                }
            }
        }
        for(int i=0; i<n; i  ){
            for(int j=0; j<n; j  ){
                System.out.print(randMatrix[i][j] "\t");
            }
            System.out.println();
        }
    }
    public static int sumLastColumn(int n, int[][]randMatrix){
        int sumCol = 0;
        for(int i=0; i<n; i  ){
            int[]row = randMatrix[i];
            sumCol  = row[row.length-1];
        }
        System.out.println("SumLastCol: " sumCol);
        return sumCol;
    }
    public static int sumRows(int n, int[][]randMatrix) {
        int sumRow = 0;
        for (int i=0; i<n; i  ) {
            sumRow = 0;
            for (int j=0; j<n; j  ) {
                sumRow = sumRow   randMatrix[i][j];
            }
            System.out.println("SumRow" (i 1) ": "   sumRow);
        }
        return sumRow;
    }
}

If you know how to do it, please help me:)

CodePudding user response:

Here's an easy way.

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

First, compute the sum of the last column.

  • stream each row
  • map the last value in the row
  • and sum them.
int lastColSum = Arrays.stream(mat).mapToInt(s->s[s.length-1]).sum();

Now just iterate across the rows, summing them and comparing to the lastColSum and reverse if required.

for (int[] row :mat) {
    if (Arrays.stream(row).sum() < lastColSum) {
        reverse(row);
    }
}

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

prints

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

Helper method to reverse the row. It works by swapping values at it moves outside toward the middle. This works for even or odd length rows.

public static void reverse(int [] v) {
    for(int i = 0; i < v.length/2; i  ) {
        int t = v[0];
        v[0] = v[v.length-i-1];
        v[v.length-i-1] = t;
    }
}
  •  Tags:  
  • java
  • Related