Skip to content

Instantly share code, notes, and snippets.

@ggPeti
Last active December 26, 2015 17:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ggPeti/7188838 to your computer and use it in GitHub Desktop.
Save ggPeti/7188838 to your computer and use it in GitHub Desktop.
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