-
-
Save vdonchev/4fc3f66b9f099a07e99e0507bd00091b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function generateSpiralMatrix(input) { | |
[rows, cols] = input.map(Number); | |
let matrix = []; | |
for (let row = 0; row < rows; row++) { | |
matrix[row] = []; | |
for (let col = 0; col < cols; col++) { | |
matrix[row][col] = 0; | |
} | |
} | |
let top = 0; | |
let bottom = rows - 1; | |
let left = 0; | |
let right = cols - 1; | |
let index = 1; | |
let direction = 0; | |
while (top <= bottom && left <= right) { | |
switch (direction % 4) { | |
case 0: | |
for (let col = left; col <= right; col++) { | |
matrix[top][col] = index++; | |
} | |
top++; | |
direction++; | |
break; | |
case 1: | |
for (let row = top; row <= bottom; row++) { | |
matrix[row][right] = index++; | |
} | |
right--; | |
direction++; | |
break; | |
case 2: | |
for (let col = right; col >= left; col--) { | |
matrix[bottom][col] = index++; | |
} | |
bottom--; | |
direction++; | |
break; | |
default: | |
for (let row = bottom; row >= top; row--) { | |
matrix[row][left] = index++; | |
} | |
left++; | |
direction++; | |
break; | |
} | |
} | |
console.log(matrix.map(r => r.join(' ')).join('\n')); | |
} | |
generateSpiralMatrix(['5', '5']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment