Skip to content

Instantly share code, notes, and snippets.

@ggPeti

ggPeti/spiral.rb

Last active Dec 26, 2015
Embed
What would you like to do?
Procedural Ruby solution for the Spiral task
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
You can’t perform that action at this time.