Skip to content

Instantly share code, notes, and snippets.

@FlameWolf
Created January 12, 2024 11:28
Show Gist options
  • Save FlameWolf/75e6f2a2bd913287c4e0e758450e4644 to your computer and use it in GitHub Desktop.
Save FlameWolf/75e6f2a2bd913287c4e0e758450e4644 to your computer and use it in GitHub Desktop.
Snail Algorithm (CodeWars Challenge)
/*
input:
[
[01, 02, 03, 04, 05, 06],
[07, 08, 09, 10, 11, 12],
[13, 14, 15, 16, 17, 18],
[19, 20, 21, 22, 23, 24],
[25, 26, 27, 28, 29, 30],
[31, 32, 33, 34, 35, 36]
];
output:
[
01, 02, 03, 04, 05, 06,
12, 18, 24, 30, 36, 35,
34, 33, 32, 31, 25, 19,
13, 07, 08, 09, 10, 11,
17, 23, 29, 28, 27, 26,
20, 14, 15, 16, 22, 21
];
*/
function snail(source) {
const result = [];
const len = source.length;
for (let loopIndex = 0; loopIndex < len; loopIndex++) {
let startX = loopIndex;
let endX = loopIndex;
let startY = loopIndex;
let endY = len - (loopIndex + 1);
for (let y = startY; y <= endY; y++) {
result.push(source[startX][y]);
}
startX += 1;
endX = len - startX;
startY = endX;
for (let x = startX; x <= endX; x++) {
result.push(source[x][startY]);
}
startX = endX;
startY -= 1;
endY = loopIndex;
for (let y = startY; y >= endY; y--) {
result.push(source[startX][y]);
}
startX -= 1;
endX = len - endX;
startY = endY;
for (let x = startX; x >= endX; x--) {
result.push(source[x][startY]);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment