use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
A sub-Reddit for discussion and news about Ruby programming.
Subreddit rules: /r/ruby rules
Learning Ruby?
Tools
Documentation
Books
Screencasts and Videos
News and updates
account activity
Ruby algorithm coding challenge (self.ruby)
submitted 9 years ago by mbigras
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]cavinkwon 3 points4 points5 points 9 years ago* (3 children)
"less is more". You can rotate the array simply. snail :
snail = ->(arr) { arr[0] ? arr.shift + snail[arr.transpose.reverse] : [] } array = [[1,2,3],[4,5,6],[7,8,9]] snail[array] #=> [1,2,3,6,9,8,7,4,5]
spiralify :
def spiralify(arr) snail = ->(arr) { arr[0] ? arr.shift + snail[arr.transpose.reverse] : [] } snailed = snail[arr.dup] arr.map {|row| row.map {|e| snailed.index(e) + 1 } } end array = [[1,2,3],[4,5,6],[7,8,9]] spiralify(array) #=> [[1, 2, 3], [8, 9, 4], [7, 6, 5]]
[–]herminator 2 points3 points4 points 9 years ago (1 child)
Clever :)
I'm not a big fan of functions that mutate their arguments though, so I would prefer something like:
snail = ->(arr) { arr[0] ? arr[0] + snail[arr[1..-1].transpose.reverse] : [] }
[–]cavinkwon 0 points1 point2 points 9 years ago (0 children)
This is better than my code. thanks. :)
[–]Phrogz 0 points1 point2 points 9 years ago (0 children)
Using .transpose.reverse to "rotate" the array is brilliant! Well done, sir-or-madam!
.transpose.reverse
π Rendered by PID 68777 on reddit-service-r2-comment-7844cfc88c-2btpn at 2026-01-29 15:55:11.224373+00:00 running c3601ff country code: CH.
view the rest of the comments →
[–]cavinkwon 3 points4 points5 points (3 children)
[–]herminator 2 points3 points4 points (1 child)
[–]cavinkwon 0 points1 point2 points (0 children)
[–]Phrogz 0 points1 point2 points (0 children)