Advertisement
Btwonu

Spiral

Jun 17th, 2020
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. function main(matrix, row) {
  4.   //Create an empty matrix
  5.   let spiralArray = createArray(matrix, row);
  6.  
  7.   let top = 0;
  8.   let bottom = matrix - 1;
  9.   let left = 0;
  10.   let right = row - 1;
  11.  
  12.   let number = 0;
  13.   while (top <= bottom && left <= right) {
  14.    
  15.     for (let i = left; i <= right; i++) {
  16.       spiralArray[top][i] = ++number;
  17.     }
  18.  
  19.     top++;
  20.  
  21.     for (let j = top; j <= bottom; j++) {
  22.       spiralArray[j][right] = ++number;
  23.     }
  24.  
  25.     right--;
  26.  
  27.     for (let k = right; k >= left; k--) {
  28.       spiralArray[bottom][k] = ++number;
  29.     }
  30.  
  31.     bottom--;
  32.  
  33.     for (let l = bottom; l >= top; l--) {
  34.       spiralArray[l][left] = ++number;
  35.     }
  36.    
  37.     left++;
  38.   }
  39.   return spiralArray;
  40.  
  41.   //Declaration
  42.   function createArray(matrix, row) {
  43.     let array = [];
  44.    
  45.     for (let i = 0; i < matrix; i++) {
  46.       let subArray = [];
  47.       subArray.length = row;
  48.       array.push(subArray);
  49.     }
  50.     return array;
  51.   }
  52. }
  53.  
  54. let result = main(5, 5);
  55. console.log(result);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement