Untitled
unknown
java
8 months ago
3.4 kB
6
Indexable
import java.util.Scanner;
/**
* Rotating every row and column in a matrix by an integer value.
* The matrix is an n x n square matrix with a list of integers exactly 2n in length.
*/
public class Design {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input of matrix dimensions n
System.out.print("Enter n: ");
int n = sc.nextInt();
// Input of matrix values row by row
int[][] matrix = new int[n][n];
System.out.println("Enter the matrix values row by row. E.g 1 2 then 3 4: ");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = sc.nextInt();
}
}
// Input 2n shift values
int[] shifts = new int[2 * n];
System.out.println("Enter " + (2 * n) + " shift values pressing enter after each one:");
for (int i = 0; i < 2 * n; i++) {
shifts[i] = sc.nextInt();
}
sc.close();
// For each i, rotate row i and then rotate column i
for (int i = 0; i < n; i++) {
// Rotate row i
rotateRow(matrix, i, shifts[2 * i], n);
// Rotate column i
rotateColumn(matrix, i, shifts[2 * i + 1], n);
}
// Display the final matrix
System.out.println("Rotated matrix:");
printMatrix(matrix, n);
}
/**
* Rotates the row at index 'rowIndex' by 'shift' steps.
* Positive shift rotates to the right; negative rotates to the left.
* Simplifies the rotation to be in the range of 0 to n-1.
*/
public static void rotateRow(int[][] matrix, int rowIndex, int shift, int n) {
// Bring the shift value in range [0, n-1]
shift = (shift % n + n) % n;
// Array to store rotated row
int[] tempRow = new int[n];
// Add to tempRow by shifting row rowIndex to the right by shift
for (int col = 0; col < n; col++) {
tempRow[(col + shift) % n] = matrix[rowIndex][col];
}
// Overwrite the old row in the matrix with tempRow
for (int col = 0; col < n; col++) {
matrix[rowIndex][col] = tempRow[col];
}
}
/**
* Rotates the column at index 'colIndex' by 'shift' steps.
* Positive shift rotates down; negative rotates up.
* Simplifies the rotation to be in the range of 0 to n-1.
*/
public static void rotateColumn(int[][] matrix, int colIndex, int shift, int n) {
// Bring the shift value in range [0, n-1]
shift = (shift % n + n) % n;
// Array to store rotated column
int[] tempCol = new int[n];
// Add to tempCol by shifting column colIndex down by shift
for (int row = 0; row < n; row++) {
tempCol[(row + shift) % n] = matrix[row][colIndex];
}
// Overwrite the old column in the matrix with tempCol
for (int row = 0; row < n; row++) {
matrix[row][colIndex] = tempCol[row];
}
}
/**
* Displays the matrix.
*/
public static void printMatrix(int[][] matrix, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
Editor is loading...
Leave a Comment