array = [[1,2,3], [4,5,6], [7,8,9]] snail(array) #=> [1,2,3,6,9,8,7,4,5]
Given an array of n * x
, return the array elements arranged from outermost elements to the middle element, traveling clockwise. Do not sort the elements from lowest to highest, instead traverse the 2-D array in a clockwise, snailshell pattern.
These examples will clarify the challenge:
array = [[1,2,3], [8,9,4], [7,6,5]] snail(array) #=> [1,2,3,4,5,6,7,8,9]
An empty matrix would be represented as [[]].
Below are some matrices to test your code on. Good luck, have fun!
(snail([[]])); (snail([[1]])); (snail([[1, 2, 3], [4, 5, 6], [7, 8, 9])); (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]])); (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]]));
Today's challenge comes from stevenbarragan on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (13)
Here it is!
It works kinda litterally:
And the results:
Solution in Python based on La blatte's wonderful implementation if anyone is interested!
Much cleaner than mine! Nicely done 🎉
I did the same thing with nearly 10x more code. Great work!
Haskell:
Python
Tricky! Not sure I found the most efficient way to do it - but it works, and I think it's relatively clean(ish) :)
Watch me solve it too: youtu.be/h-OzkY1_8mU
Hey Chris, I made a replica of your solution translated to Python3.5 or greater.
It only works where both of the lengths of the arrays are equal. Otherwise, it adds cute 'undefined' in the end. Also, these if checks are there for safety. They may be ugly and repetitive but I did not want the calculate every other case.
A different take, this one might not appear as elegant, but it is quite a lot faster than the previous variants:
So there was supposed to be an image attached, but it doesn't seem to work, anyhow, for those curious JSBench.me gives the following results:
Above one
2,508,265 ops/s ±0.46%
Chris Achards
411,247 ops/s ±1.04%
La blattes
364,899 ops/s ±3.35%
(Firefox, Windows)
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]]);
Reminds me of this task on Exercism :)
Cool task from hackerrank :)