Advertisement
Guest User

Untitled

a guest
May 26th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function spiralMatrix(rows, cols) {
  2.     let targetNum = rows * cols;
  3.     let number = 1;
  4.     let matrix = fillMatrixWithZeros(rows, cols);
  5.  
  6.     let currentRow = 0;
  7.     let currentCol = 0;
  8.     let rotations = 0;
  9.  
  10.     for(let i = 0; i <= rows / 2; i++)
  11.     {
  12.         for (let index = rotations; index < cols - rotations; index++) {
  13.             matrix[currentRow][currentCol++] = number++;
  14.         }
  15.         currentCol--;
  16.         for (let index = ++currentRow; index <= rows - 1 - rotations; index++) {
  17.             matrix[currentRow++][currentCol] = number++;
  18.         }
  19.         currentRow--;
  20.         for (let index = --currentCol; index >= rotations ; index--) {
  21.             matrix[currentRow][currentCol--] = number++;
  22.         }
  23.         currentCol++;
  24.         for (let index = --currentRow; index > rotations; index--) {
  25.             matrix[currentRow--][currentCol] = number++;
  26.         }
  27.         rotations++;
  28.         currentCol++;
  29.         currentRow++;
  30.     }
  31.     printMatrix(matrix)
  32.     function fillMatrixWithZeros(rows, cols) {
  33.         let matrix = [];
  34.         for (let row = 0; row < rows; row++) {
  35.             matrix.push('0'
  36.                 .repeat(cols)
  37.                 .split('')
  38.                 .map(Number));
  39.         }
  40.         return matrix;
  41.     }
  42.     function printMatrix(matrix) {
  43.         console.log(matrix.map(x => x.join(' ')).join('\n'));
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement