Created
November 13, 2020 12:16
-
-
Save schadokar/642927b329b8b2b458938cd6a574957e to your computer and use it in GitHub Desktop.
Create a spiral matrix
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
// --- Directions | |
// Write a function that accepts an integer N | |
// and returns a NxN spiral matrix. | |
// --- Examples | |
// matrix(2) | |
// [[1, 2], | |
// [4, 3]] | |
// matrix(3) | |
// [[1, 2, 3], | |
// [8, 9, 4], | |
// [7, 6, 5]] | |
// matrix(4) | |
// [[1, 2, 3, 4], | |
// [12, 13, 14, 5], | |
// [11, 16, 15, 6], | |
// [10, 9, 8, 7]] | |
function matrix(n) { | |
const result = []; | |
for (let i = 0; i < n; i++) { | |
result.push([]); | |
} | |
let startRow = 0; | |
let endRow = n - 1; | |
let startCol = 0; | |
let endCol = n - 1; | |
let count = 1; | |
while (startRow <= endRow && startCol <= endCol) { | |
// fill start row from left to right and increment the startRow by 1 | |
for(let i = startCol; i <= endCol; i++) { | |
result[startRow][i] = count; | |
count++; | |
} | |
// increment the startRow | |
startRow += 1; | |
// fill the end column from top to bottom and decrement the endCol by 1 | |
for(let i = startRow; i <= endRow; i++) { | |
result[i][endCol] = count; | |
count++ | |
} | |
// decrement the endCol | |
endCol -= 1; | |
// fill the endRow from right to left and decrement the endRow by 1 | |
for(let i = endCol; i >= startCol; i--) { | |
result[endRow][i] = count; | |
count++ | |
} | |
// decrement the end row | |
endRow -= 1 | |
// fill the startCol from bottom to top and increment the startCol by 1 | |
for(let i = endRow; i >= startRow; i--) { | |
result[i][startCol] = count; | |
count++; | |
} | |
startCol += 1; | |
// break; | |
} | |
return result; | |
} | |
// matrix(5); | |
module.exports = matrix; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment