Skip to content

Instantly share code, notes, and snippets.

@vvgomes
Last active March 22, 2021 20:37
Show Gist options
  • Save vvgomes/c72de022c14eca14147e416ef083862f to your computer and use it in GitHub Desktop.
Save vvgomes/c72de022c14eca14147e416ef083862f to your computer and use it in GitHub Desktop.
/*
[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