Advertisement
dimipan80

String Matrix Rotation

Dec 18th, 2014
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* You are given a sequence of text lines. Assume these text lines form a matrix of characters
  2. (pad the missing positions with spaces to build a rectangular matrix).Write a program to rotate the matrix
  3. by 90, 180, 270, 360, … degrees. Print the result at the console as sequence of strings. */
  4.  
  5. "use strict";
  6.  
  7. function rotateTheStringMatrix(args) {
  8.     var rotate = Number(args[0].split(/\D+/).filter(Boolean));
  9.     rotate %= 360;
  10.  
  11.     var i;
  12.     var matrix = [];
  13.     var maxStringLength = 1;
  14.     for (i = 1; i < args.length; i += 1) {
  15.         if (args[i].length > maxStringLength) {
  16.             maxStringLength = args[i].length;
  17.         }
  18.         matrix.push(args[i].split('').filter(Boolean));
  19.     }
  20.  
  21.     for (i = 0; i < matrix.length; i += 1) {
  22.         while (matrix[i].length < maxStringLength) {
  23.             matrix[i].push(' ');
  24.         }
  25.     }
  26.  
  27.     function rotateToNext90Degrees(matrix) {
  28.         var maxLengthRow = matrix.length;
  29.         var maxLengthCol = matrix[0].length;
  30.         var newMatrix = new Array(maxLengthCol);
  31.         for (var col = 0; col < maxLengthCol; col += 1) {
  32.             newMatrix[col] = new Array(maxLengthRow);
  33.             for (var row = 0; row < maxLengthRow; row += 1) {
  34.                 newMatrix[col][maxLengthRow - row - 1] = matrix[row][col];
  35.             }
  36.         }
  37.  
  38.         return newMatrix;
  39.     }
  40.  
  41.     while (rotate > 0) {
  42.         matrix = rotateToNext90Degrees(matrix);
  43.         rotate -= 90;
  44.     }
  45.  
  46.     for (var row in matrix) {
  47.         if (matrix.hasOwnProperty(row)) {
  48.             console.log(matrix[row].join(''));
  49.         }
  50.     }
  51. }
  52.  
  53. rotateTheStringMatrix([
  54.     'Rotate(90)',
  55.     'hello',
  56.     'softuni',
  57.     'exam'
  58. ]);
  59.  
  60. rotateTheStringMatrix([
  61.     'Rotate(180)',
  62.     'hello',
  63.     'softuni',
  64.     'exam'
  65. ]);
  66.  
  67. rotateTheStringMatrix([
  68.     'Rotate(270)',
  69.     'hello',
  70.     'softuni',
  71.     'exam'
  72. ]);
  73.  
  74. rotateTheStringMatrix([
  75.     'Rotate(720)',
  76.     'js',
  77.     'exam'
  78. ]);
  79.  
  80. rotateTheStringMatrix([
  81.     'Rotate(810)',
  82.     'js',
  83.     'exam'
  84. ]);
  85.  
  86. rotateTheStringMatrix([
  87.     'Rotate(0)',
  88.     'js',
  89.     'exam'
  90. ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement