Advertisement
Guest User

matrix shufling

a guest
May 23rd, 2018
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.24 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. /**
  4.  * Created by IntelliJ IDEA.
  5.  * User: LAPD
  6.  * Date: 22.5.2018 г.
  7.  * Time: 08:56 ч.
  8.  */
  9. public class _05MatrixShuffling {
  10.     public static void main(String[] args) {
  11.         Scanner console = new Scanner(System.in);
  12.  
  13.         int rows = console.nextInt();
  14.         int cols = console.nextInt();
  15.         console.nextLine();
  16.  
  17.         String[][] matrix = new String[rows][cols];
  18.  
  19.         for (int row = 0; row < rows; row++) {
  20.             String[] rowValues = console.nextLine()
  21.                     .split("\\s+");
  22.  
  23.             for (int col = 0; col < cols; col++) {
  24.                 matrix[row][col] = rowValues[col];
  25.             }
  26.         }
  27.  
  28.         String input = "";
  29.         while (!"END".equals(input = console.nextLine())) {
  30.  
  31.             String[] commandArgs = input.split("\\s+");
  32.  
  33.             if (!"swap".equals(commandArgs[0])
  34.                     || commandArgs.length != 5) {
  35.                 System.out.println("Invalid input!");
  36.                 continue;
  37.             }
  38.  
  39.             int row1;
  40.             int col1;
  41.             int row2;
  42.             int col2;
  43.  
  44.             try {
  45.                 row1 = Integer.parseInt(commandArgs[1]);
  46.                 col1 = Integer.parseInt(commandArgs[2]);
  47.                 row2 = Integer.parseInt(commandArgs[3]);
  48.                 col2 = Integer.parseInt(commandArgs[4]);
  49.             } catch (Exception e) {
  50.                 System.out.println("Invalid input!");
  51.                 continue;
  52.             }
  53.  
  54.             if (row1 >= rows || col1 >= cols
  55.                     || row2 >= rows || col2 >= cols) {
  56.                 System.out.println("Invalid input!");
  57.                 continue;
  58.             }
  59.  
  60.             String temp = matrix[row1][col1];
  61.             matrix[row1][col1] = matrix[row2][col2];
  62.             matrix[row2][col2] = temp;
  63.  
  64.             printMatrix(matrix);
  65.         }
  66.     }
  67.  
  68.     private static void printMatrix(String[][] matrix) {
  69.         for (int i = 0; i < matrix.length; i++) {
  70.             StringBuilder row = new StringBuilder();
  71.  
  72.             for (int j = 0; j < matrix[i].length; j++) {
  73.                 row.append(matrix[i][j]).append(" ");
  74.             }
  75.  
  76.             System.out.println(row.toString().trim());
  77.         }
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement