Skip to content

Instantly share code, notes, and snippets.

@cxspxr
Created March 5, 2021 14:14
Show Gist options
  • Save cxspxr/2011a2f9c5344ee446d725b74db5ce0f to your computer and use it in GitHub Desktop.
Save cxspxr/2011a2f9c5344ee446d725b74db5ce0f to your computer and use it in GitHub Desktop.
snail sort solution for Ilya
const snail = (arr) => {
if (arr.length === 1) return arr[0]
let right = arr.length - 1,
bottom = right,
left = 0,
top = 1;
const result = [arr[0][0]]
let rowIndex = 0,
columnIndex = 0;
while (result.length !== arr.length * arr.length) {
while (columnIndex < right) {
columnIndex++;
result.push(arr[rowIndex][columnIndex])
}
right--;
while (rowIndex < bottom) {
rowIndex++;
result.push(arr[rowIndex][columnIndex])
}
bottom--;
while (columnIndex > left) {
columnIndex--;
result.push(arr[rowIndex][columnIndex])
}
left++;
while (rowIndex > top) {
rowIndex--;
result.push(arr[rowIndex][columnIndex])
}
top++;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment