Created
March 5, 2021 14:14
-
-
Save cxspxr/2011a2f9c5344ee446d725b74db5ce0f to your computer and use it in GitHub Desktop.
snail sort solution for Ilya
This file contains hidden or 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
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