Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Uprajnenie;
- import java.util.Scanner;
- public class MatrixShuffling {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- // Read matrix dimensions
- int rows = scanner.nextInt();
- int cols = scanner.nextInt();
- scanner.nextLine(); // Consume newline
- // Read the matrix
- String[][] matrix = new String[rows][cols];
- for (int i = 0; i < rows; i++) {
- String[] rowValues = scanner.nextLine().split("\\s+");
- for (int j = 0; j < cols; j++) {
- matrix[i][j] = rowValues[j];
- }
- }
- // Perform operations
- while (true) {
- String command = scanner.nextLine();
- if (command.equals("END")) {
- break;
- }
- String[] tokens = command.split("\\s+");
- if (tokens.length != 5 || !tokens[0].equals("swap")) {
- System.out.println("Invalid input!");
- continue;
- }
- try {
- int row1 = Integer.parseInt(tokens[1]);
- int col1 = Integer.parseInt(tokens[2]);
- int row2 = Integer.parseInt(tokens[3]);
- int col2 = Integer.parseInt(tokens[4]);
- if (!isValidCell(matrix, row1, col1) || !isValidCell(matrix, row2, col2)) {
- System.out.println("Invalid input!");
- continue;
- }
- String temp = matrix[row1][col1];
- matrix[row1][col1] = matrix[row2][col2];
- matrix[row2][col2] = temp;
- printMatrix(matrix);
- } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
- System.out.println("Invalid input!");
- }
- }
- }
- // Method to check if a cell is valid
- private static boolean isValidCell(String[][] matrix, int row, int col) {
- return row >= 0 && row < matrix.length && col >= 0 && col < matrix[0].length;
- }
- // Method to print the matrix
- private static void printMatrix(String[][] matrix) {
- for (String[] row : matrix) {
- for (String cell : row) {
- System.out.print(cell + " ");
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement