Skip to content

Instantly share code, notes, and snippets.

@astambi
Created October 12, 2016 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astambi/ca990efbb6b00c410ff300dd8538ab39 to your computer and use it in GitHub Desktop.
Save astambi/ca990efbb6b00c410ff300dd8538ab39 to your computer and use it in GitHub Desktop.
Spiral Matrix
function spiralMatrix([arr]) {
printMatrix(getMatrix(arr));
function getMatrix(arr) {
let [rows, cols] = arr.split(' ')
.filter(x => x != '')
.map(Number);
let [count, maxCount, minRow, minCol, maxRow, maxCol] = [0, rows * cols, 0, 0, rows-1, cols-1];
let matrix = [];
for (let r = 0; r < rows; r++) matrix[r] = [];
while (count < maxCount) {
for (let c = minCol; c <= maxCol && count < maxCount; c++) matrix[minRow][c] = ++count;
minRow++;
for (let r = minRow; r <= maxRow && count < maxCount; r++) matrix[r][maxCol] = ++count;
maxCol--;
for (let c = maxCol; c >= minCol && count < maxCount; c--) matrix[maxRow][c] = ++count;
maxRow--;
for (let r = maxRow; r >= minRow && count < maxCount; r--) matrix[r][minCol] = ++count;
minCol++;
}
return matrix;
}
function printMatrix(matrix) {
matrix.forEach(row => console.log(row.join(' ')));
// console.log(matrix.map(row => row.join(' ')).join('\n'));
}
}
spiralMatrix(['5 5']);
spiralMatrix(['3 3']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment