Advertisement
dimipan80

Exams - String Matrix Rotation

Nov 17th, 2014
171
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
  3. the matrix by 90, 180, 270, 360, … degrees. Print the result at the console as sequence of strings. */
  4.  
  5. "use strict";
  6.  
  7. function rotateTheMatrix(arr) {
  8.     var rotate = parseInt(arr[0].substring(7, arr[0].length - 1)) % 360;
  9.  
  10.     var matrix = [];
  11.     var maxLength = 1;
  12.     for (var i = 1; i < arr.length; i += 1) {
  13.         var matrixRow = arr[i].split('').filter(Boolean);
  14.         if (matrixRow.length > maxLength) {
  15.             maxLength = matrixRow.length;
  16.         }
  17.         matrix.push(matrixRow);
  18.     }
  19.  
  20.     for (i = 0; i < matrix.length; i += 1) {
  21.         while (matrix[i].length < maxLength) {
  22.             matrix[i].push(' ');
  23.         }
  24.     }
  25.  
  26.     var output = '';
  27.     if (rotate == 0) {
  28.         for (i = 0; i < matrix.length; i += 1) {
  29.             output = output.concat(matrix[i].join('')).concat('\n');
  30.         }
  31.         return output;
  32.     }
  33.  
  34.     if (rotate == 180) {
  35.         for (i = matrix.length - 1; i >= 0; i -= 1) {
  36.             var rowStr = matrix[i].reverse().join('');
  37.             output = output.concat(rowStr).concat('\n');
  38.         }
  39.         return output;
  40.     }
  41.  
  42.     var rotatedArr = new Array(maxLength);
  43.     for (i = 0; i < rotatedArr.length; i += 1) {
  44.         rotatedArr[i] = [];
  45.         for (var j= matrix.length - 1; j >= 0; j -= 1) {
  46.             rotatedArr[i].push(matrix[j][i]);
  47.         }
  48.     }
  49.  
  50.     if (rotate == 90) {
  51.         for (i = 0; i < rotatedArr.length; i += 1) {
  52.             rowStr = rotatedArr[i].join('');
  53.             output = output.concat(rowStr).concat('\n');
  54.         }
  55.         return output;
  56.     }
  57.  
  58.     if (rotate == 270) {
  59.         for (i = rotatedArr.length - 1; i >= 0; i -= 1) {
  60.             rowStr = rotatedArr[i].reverse().join('');
  61.             output = output.concat(rowStr).concat('\n');
  62.         }
  63.         return output;
  64.     }
  65. }
  66.  
  67. console.log(rotateTheMatrix([ 'Rotate(90)', 'hello', 'softuni', 'exam' ]));
  68. console.log(rotateTheMatrix([ 'Rotate(180)', 'hello', 'softuni', 'exam' ]));
  69. console.log(rotateTheMatrix([ 'Rotate(270)', 'hello', 'softuni', 'exam' ]));
  70. console.log(rotateTheMatrix([ 'Rotate(720)', 'js', 'exam' ]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement