Created
September 12, 2018 21:21
-
-
Save arrbxr/5cced401e6b08c4d6dd8e875c63226e0 to your computer and use it in GitHub Desktop.
matrix spiral problem created by arrbxr - https://repl.it/@arrbxr/matrix-spiral-problem
This file contains hidden or 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) { | |
let result = []; | |
for(let i = 0; i < n; i++) { | |
result.push([]); | |
} | |
let counter = 1; | |
let startColun = 0; | |
let endColumn = n - 1; | |
let startRow = 0; | |
let endRow = n - 1; | |
while(startColun <= endColumn && startRow <= endRow) { | |
// Top row | |
for(let i = startColun; i <= endColumn; i++) { | |
result[startRow][i] = counter; | |
counter++; | |
} | |
startRow++; | |
// Right column | |
for(let i = startRow; i <= endRow; i++) { | |
result[i][endColumn] = counter; | |
counter++; | |
} | |
endColumn--; | |
// Bottom row | |
for(let i = endColumn; i >= startColun; i--) { | |
result[endRow][i] = counter; | |
counter++; | |
} | |
endRow--; | |
// start column | |
for(let i = endRow; i >= startRow; i--) { | |
result[i][startColun] = counter; | |
counter++; | |
} | |
startColun++; | |
} | |
return result; | |
} | |
matrix(5); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment