What would be the most basic way to shift the rows of a 2d array in java down by 1. The first row turns into the second row, the second row turns into the third row and the last row turns into the first one.
I tried this but it only lets me change two rows.
public static void switchRows(int[][] matrix, int K, int L){
for (int i = 0; i < matrix[0].length; i++) {
// Swap two numbers
int temp = matrix[K - 1][i];
matrix[K - 1][i] = matrix[L - 1][i];
matrix[L - 1][i] = temp;
}
// Print matrix
for(int g = 0; g < matrix.length; g++){
for(int b = 0; b < matrix[g].length; b++){
System.out.print(matrix[g][b] + " ");
}
System.out.println();
}
}
>Solution :
For this problem first, you need to create a copy of the array that represents the last row (lastRow).
After that, all values for each row (except the first row matrix[0]) have to be overwritten with values from the previous row.
Finally, assign the reference to the defensive copy of last row to the first row of the matrix.
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
switchRows(matrix);
printMatrix(matrix);
}
public static void switchRows(int[][] matrix){
int[] lastRow = Arrays.copyOf(matrix[matrix.length - 1], matrix[matrix.length - 1].length);
for (int row = matrix.length - 1; row > 0; row--) {
// assign values of the previous row to current row
for (int col = 0; col < matrix[row].length; col++) {
matrix[row][col] = matrix[row - 1][col];
}
}
matrix[0] = lastRow;
}
public static void printMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++){
for(int col = 0; col < matrix[row].length; col++){
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
output
7 8 9
1 2 3
4 5 6