Untitled
unknown
java
8 days ago
2.4 kB
17
Indexable
public class Design { public static void main(String[] args) { // initialise size and contents of matrix int n = 3; int[][] matrix = { {1, 2, -3}, {-4, 5, 6}, {7, -8, 0} }; // initialise integers the rows and columns shift by int[] shifts = {1,-2,0,-1,3,4}; // For each i rotate row i and then rotate column i for (int i = 0; i < n; i++) { // Rotate row i int rowShift = shifts[2 * i]; // Simplifies rotation by a large number // For example a rotation of -3 is shifting left 3 times // This is equivalent to a rotation of 1 // It can be simplified to be in the range of 0 to n-1 rowShift = (rowShift % n + n) % n; // Array to store rotated row int[] tempRow = new int[n]; // Add to tempRow by shifting row i to the right by rowShift for (int col = 0; col < n; col++) { tempRow[(col + rowShift) % n] = matrix[i][col]; } // Overwrite the old row in the matrix defined by replacing that row with tempRow for (int col = 0; col < n; col++) { matrix[i][col] = tempRow[col]; } // Rotate column i int colShift = shifts[2 * i + 1]; // Simplifying the rotation to a rotation up between 0 and n-1 colShift = (colShift % n + n) % n; // Array to store rotated column int[] tempCol = new int[n]; // Add to tempCol by shifting col i to the right by colShift for (int row = 0; row < n; row++) { tempCol[(row + colShift) % n] = matrix[row][i]; } // Overwrite the old column in the matrix defined by replacing that column with tempCol for (int row = 0; row < n; row++) { matrix[row][i] = tempCol[row]; } } // Display the final matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(matrix[i][j]); if (j < n - 1) { System.out.print(" "); } } System.out.println(); } } }
Editor is loading...
Leave a Comment