Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* You are given a sequence of text lines. Assume these text lines form a matrix of characters
- (pad the missing positions with spaces to build a rectangular matrix). Write a program to rotate
- the matrix by 90, 180, 270, 360, … degrees. Print the result at the console as sequence of strings. */
- "use strict";
- function rotateTheMatrix(arr) {
- var rotate = parseInt(arr[0].substring(7, arr[0].length - 1)) % 360;
- var matrix = [];
- var maxLength = 1;
- for (var i = 1; i < arr.length; i += 1) {
- var matrixRow = arr[i].split('').filter(Boolean);
- if (matrixRow.length > maxLength) {
- maxLength = matrixRow.length;
- }
- matrix.push(matrixRow);
- }
- for (i = 0; i < matrix.length; i += 1) {
- while (matrix[i].length < maxLength) {
- matrix[i].push(' ');
- }
- }
- var output = '';
- if (rotate == 0) {
- for (i = 0; i < matrix.length; i += 1) {
- output = output.concat(matrix[i].join('')).concat('\n');
- }
- return output;
- }
- if (rotate == 180) {
- for (i = matrix.length - 1; i >= 0; i -= 1) {
- var rowStr = matrix[i].reverse().join('');
- output = output.concat(rowStr).concat('\n');
- }
- return output;
- }
- var rotatedArr = new Array(maxLength);
- for (i = 0; i < rotatedArr.length; i += 1) {
- rotatedArr[i] = [];
- for (var j= matrix.length - 1; j >= 0; j -= 1) {
- rotatedArr[i].push(matrix[j][i]);
- }
- }
- if (rotate == 90) {
- for (i = 0; i < rotatedArr.length; i += 1) {
- rowStr = rotatedArr[i].join('');
- output = output.concat(rowStr).concat('\n');
- }
- return output;
- }
- if (rotate == 270) {
- for (i = rotatedArr.length - 1; i >= 0; i -= 1) {
- rowStr = rotatedArr[i].reverse().join('');
- output = output.concat(rowStr).concat('\n');
- }
- return output;
- }
- }
- console.log(rotateTheMatrix([ 'Rotate(90)', 'hello', 'softuni', 'exam' ]));
- console.log(rotateTheMatrix([ 'Rotate(180)', 'hello', 'softuni', 'exam' ]));
- console.log(rotateTheMatrix([ 'Rotate(270)', 'hello', 'softuni', 'exam' ]));
- console.log(rotateTheMatrix([ 'Rotate(720)', 'js', 'exam' ]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement