Created
June 15, 2022 22:40
-
-
Save jhubble/8ad7c9370b76ab78c44ad0540898a82f to your computer and use it in GitHub Desktop.
Spiral or Snail sort
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
// Sort an array in "Spiral" fashion, something like a snail | |
const spiral = (arr) => { | |
let out = []; | |
let k; | |
while (arr.length) { | |
// top | |
while (k = arr[0].shift()) { out.push(k); } | |
arr.shift(); | |
if (!arr.length) { | |
return out; | |
} | |
//right | |
for (let i=0;i<arr.length; i++) { | |
out.push(arr[i].pop()); | |
} | |
//bottom | |
while (k = arr[arr.length-1].pop()) { out.push(k)} | |
arr.pop(); | |
//left | |
for (let i=arr.length-1;i>=0;i--) { | |
out.push(arr[i].shift()); | |
} | |
} | |
return out; | |
} | |
const arr = [[1,2,3,4], | |
[12,13,14,5], | |
[11,16,15,6], | |
[10,9,8,7] | |
]; | |
console.log(spiral(arr)); | |
console.log(spiral([[1,2],[4,3]])); | |
console.log(spiral([[1,2,3],[8,9,4],[7,6,5]])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment