didkoslawow

Untitled

Feb 2nd, 2023
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function spiralMatrix(rows, columns) {
  2.     const spiralMatrix = [];
  3.  
  4.     for (let i = 0; i < rows; i++) {
  5.         spiralMatrix.push([]);
  6.     }
  7.  
  8.     let counter = 1;
  9.  
  10.     let startRow = 0;
  11.     let endRow = rows - 1;
  12.     let startColumn = 0;
  13.     let endColumn = columns - 1;
  14.  
  15.     while (startColumn <= endColumn && startRow <= endRow) {
  16.         for (let i = startColumn; i <= endColumn; i++) {
  17.             spiralMatrix[startRow][i] = counter;
  18.             counter++;
  19.         }
  20.         startRow++;
  21.  
  22.         for (let i = startRow; i <= endRow; i++) {
  23.             spiralMatrix[i][endColumn] = counter;
  24.             counter++;
  25.         }
  26.         endColumn--;
  27.  
  28.         for (let i = endColumn; i >= startColumn; i--) {
  29.             spiralMatrix[endRow][i] = counter;
  30.             counter++;
  31.         }
  32.         endRow--;
  33.  
  34.         for (let i = endRow; i >= startRow; i--) {
  35.             spiralMatrix[i][startColumn] = counter;
  36.             counter++;
  37.         }
  38.         startColumn++;
  39.     }
  40.  
  41.    
  42.     for (let i = 0; i < rows; i++) {
  43.         console.log(spiralMatrix.shift().join(' '));
  44.     }
  45. }
Add Comment
Please, Sign In to add comment