Didart

Matrix shuffling

Jan 14th, 2023
514
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 KB | None | 0 0
  1. package MultidimensionalArrays2;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class MatrixShuffling {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.         int rows = scanner.nextInt();
  10.         int cols = scanner.nextInt();
  11.         scanner.nextLine();
  12.  
  13.         String[][] matrix = new String[rows][cols];
  14.  
  15.         for (int row = 0; row < rows; row++) {
  16.             matrix[row] = scanner.nextLine().split("\\s+");
  17.         }
  18.  
  19.         String input = scanner.nextLine();
  20.         while (!"END".equals(input)) {
  21.             String[] tokens = input.split("\\s+");
  22.  
  23.             if (!"swap".equals(tokens[0])) {
  24.                 System.out.println("Invalid input!");
  25.             } else {
  26.                 try {
  27.                     int row1 = Integer.parseInt(tokens[1]);
  28.                     int col1 = Integer.parseInt(tokens[2]);
  29.                     int row2 = Integer.parseInt(tokens[3]);
  30.                     int col2 = Integer.parseInt(tokens[4]);
  31.                     swapValues(matrix, row1, col1, row2, col2);
  32.                     printMatrix(matrix);
  33.                 } catch (Exception e) {
  34.                     System.out.println("Invalid input!");
  35.                 }
  36.             }
  37.             input = scanner.nextLine();
  38.         }
  39.        
  40.     }
  41.  
  42.     private static void swapValues(String[][] matrix, int row1, int col1, int row2, int col2) {
  43.         String temporaryValue = matrix[row1][col1];
  44.         matrix[row1][col1] = matrix[row2][col2];
  45.         matrix[row2][col2] = temporaryValue;
  46.     }
  47.  
  48.     static void printMatrix(String[][] matrix) {
  49.         for (int row = 0; row < matrix.length; row++) {
  50.             for (int col = 0; col < matrix[0].length; col++) {
  51.                 System.out.print(matrix[row][col] + " ");
  52.             }
  53.             System.out.println();
  54.         }
  55.     }
  56.  
  57. }
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
Advertisement
Add Comment
Please, Sign In to add comment