Advertisement
msmilkoff

MatrixShuffling

Sep 20th, 2015
380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.30 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. class MatrixShuffling
  7. {
  8.     static void Main()
  9.     {
  10.         Console.Write("Enter matrix dimensons: ");
  11.         int[] dimentions = Console.ReadLine().Split().Select(int.Parse).ToArray();
  12.         int rows = dimentions[0];
  13.         int cols = dimentions[1];
  14.         if (dimentions.Length != 2)
  15.         {
  16.             Console.WriteLine("Invalid input: You must enter 2 dimensions");
  17.             return;
  18.         }
  19.  
  20.         // Reading the matrix row by row.
  21.         string[,] matrix = new string[rows,cols];
  22.         for (int row = 0; row < rows; row++)
  23.         {
  24.             string[] line = Console.ReadLine().Split().ToArray();
  25.  
  26.             if (line.Length > cols)
  27.             {
  28.                 throw new FormatException("Invalid input");
  29.             }
  30.  
  31.             for (int col = 0; col < cols; col++)
  32.             {
  33.                 matrix[row, col] = line[col];
  34.             }
  35.         }
  36.         PrintMatrix(matrix);
  37.  
  38.         //Swapping logic.
  39.         string[] commands = new string[5];
  40.         while (commands.Length != 1 && commands[0] != "END")
  41.         {
  42.             commands = Console.ReadLine().Split().ToArray();
  43.             if (commands.Length == 5 && commands[0] == "swap")
  44.             {
  45.                 int x1 = int.Parse(commands[1]);
  46.                 int y1 = int.Parse(commands[2]);
  47.                 int x2 = int.Parse(commands[3]);
  48.                 int y2 = int.Parse(commands[4]);
  49.  
  50.                 string temp = matrix[x1, y1];
  51.                 matrix[x1, y1] = matrix[x2, y2];
  52.                 matrix[x2, y2] = temp;
  53.  
  54.                 PrintMatrix(matrix);
  55.                
  56.                
  57.             }
  58.             else if (commands[0] == "END")
  59.             {
  60.                 break;
  61.             }
  62.             else
  63.             {
  64.                 Console.WriteLine("Invalid Input");
  65.                 return;
  66.             }
  67.            
  68.         }
  69.     }
  70.  
  71.     //Printing Method.
  72.     static void PrintMatrix(string[,] matrix)
  73.     {
  74.         for (int i = 0; i < matrix.GetLength(0); i++)
  75.         {
  76.             for (int j = 0; j < matrix.GetLength(1); j++)
  77.             {
  78.                 Console.Write(" " + matrix[i, j] + "\t");
  79.             }
  80.             Console.WriteLine();
  81.         }
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement