Created
January 5, 2018 06:49
-
-
Save eldyvoon/812507e12f2f0482325f4f5712e8cc33 to your computer and use it in GitHub Desktop.
Matrix Spiral in JavaScript
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
//specs | |
matrix(2) | |
[[1,2], | |
[4,3]] | |
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 counter = 1; | |
let startColumn = 0; | |
let endColumn = n - 1; | |
let startRow = 0; | |
let endRow = n - 1; | |
while (startColumn <= endColumn && startRow <= endRow) { | |
for (let i = startColumn; i <= endColumn; i++) { | |
result[startRow][i] = counter; | |
counter++; | |
} | |
startRow++; | |
for (let i = startRow; i <= endRow; i++) { | |
result[i][endColumn] = counter; | |
counter++; | |
} | |
endColumn--; | |
for (let i = endColumn; i >= startColumn; i--) { | |
result[endRow][i] = counter; | |
counter++; | |
} | |
endRow--; | |
for (let i = endRow; i >= startRow; i--) { | |
result[i][startColumn] = counter; | |
counter++; | |
} | |
startColumn++; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment