Last active
December 26, 2015 17:39
-
-
Save ggPeti/7188838 to your computer and use it in GitHub Desktop.
Procedural Ruby solution for the Spiral task
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
def spiral(h, w, r, c) | |
spiral = [] | |
step_counts = (1..Float::INFINITY).lazy.flat_map { |n| [n, n] } | |
directions = [:up, :left, :down, :right].cycle | |
while spiral.length < h * w | |
spiral << (r - 1) * w + c if r.between?(1, h) && c.between?(1, w) | |
if (current_step_count ||= 0).zero? | |
current_step_count = step_counts.next | |
current_direction = directions.next | |
end | |
case current_direction | |
when :up then r -= 1 | |
when :down then r += 1 | |
when :left then c -= 1 | |
when :right then c += 1 | |
end | |
current_step_count -= 1 | |
end | |
spiral | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment