Created
September 25, 2018 15:06
-
-
Save spektraldevelopment/f3503edd5b80ee422ae2827e5bf2c683 to your computer and use it in GitHub Desktop.
JS: Spiralling 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
function matrix(n) { | |
const results = []; | |
for (let i = 0; i < n; i++) { | |
results.push([]); | |
} | |
let counter = 1; | |
let startColumn = 0; | |
let endColumn = n - 1; | |
let startRow = 0; | |
let endRow = n - 1; | |
while (startColumn <= endColumn && startRow <= endRow) { | |
// Top row | |
for (let i = startColumn; i <= endColumn; i++) { | |
results[startRow][i] = counter; | |
counter++; | |
} | |
startRow++; | |
// Right column | |
for (let i = startRow; i <= endRow; i++) { | |
results[i][endColumn] = counter; | |
counter++; | |
} | |
endColumn--; | |
// Bottom row | |
for (let i = endColumn; i >= startColumn; i--) { | |
results[endRow][i] = counter; | |
counter++; | |
} | |
endRow--; | |
// start column | |
for (let i = endRow; i >= startRow; i--) { | |
results[i][startColumn] = counter; | |
counter++; | |
} | |
startColumn++; | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment