Last active
March 22, 2021 20:37
-
-
Save vvgomes/c72de022c14eca14147e416ef083862f to your computer and use it in GitHub Desktop.
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
/* | |
[1] => 1 | |
[1, 2] | |
[4, 5] => 1, 2, 5, 4 | |
[1, 2, 3] | |
[4, 5, 6] | |
[7, 8, 9] => 1, 2, 3, 6, 9, 8, 7, 4, 5 | |
*/ | |
console.log(spiral([[1, 2, 3], [4, 5, 6], [7, 8, 9]])); | |
function spiral(matrix) { | |
let result = []; | |
while (matrix.length > 0) { | |
const topRow = matrix.shift(); | |
const rightCol = matrix.map(row => row.pop()); | |
const bottomRow = (matrix.pop() || []).reverse(); | |
const leftCol = (matrix.map(row => row.shift()) || []).reverse(); | |
result = result | |
.concat(topRow) | |
.concat(rightCol) | |
.concat(bottomRow) | |
.concat(leftCol); | |
} | |
return result.join(", "); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment