## DEV Community is a community of 620,623 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Discussion on: Daily Challenge #59 - Snail Sort

La blatte

Here it is!

``````snail = arr =>
arr.length > 1
? [
...arr.shift(),
...arr.map(e => e.pop()),
...arr.pop().reverse(),
...arr.reverse().map(e => e.shift())
].concat(arr.length ? snail(arr.reverse()) : [])
: arr[0];
``````

It works kinda litterally:

• Take the first line of the array
• Add every remaining last element
• Add the last line, reversed
• Reverse the array, and return every first element
• Restart, with the remaining elements

And the results:

``````snail([[]])
[]
snail([[1]])
[1]
snail([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]);
(9) [1, 2, 3, 6, 9, 8, 7, 4, 5]
snail([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]]);
(25) [1, 2, 3, 4, 5, 10, 15, 20, 25, 24, 23, 22, 21, 16, 11, 6, 7, 8, 9, 14, 19, 18, 17, 12, 13]
snail([[1, 2, 3, 4, 5, 6],
[20, 21, 22, 23, 24, 7],
[19, 32, 33, 34, 25, 8],
[18, 31, 36, 35, 26, 9],
[17, 30, 29, 28, 27, 10],
[16, 15, 14, 13, 12, 11]])
(36) [1, 2, 3, 4, 5, 6, 7, 8, 9, 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]
``````
Melvin Yeo

Solution in Python based on La blatte's wonderful implementation if anyone is interested!

``````def snail(arr):
return arr[0] if len(arr) == 1 else [*arr.pop(0), *[elem.pop() for elem in arr], *arr.pop()[::-1], *[elem.pop(0) for elem in arr[::-1]]] + snail(arr) if len(arr) else []
``````
Chris Achard

Much cleaner than mine! Nicely done 🎉

Cagatay Kaya

I did the same thing with nearly 10x more code. Great work!