Skip to content

Instantly share code, notes, and snippets.

@kitlangton
Last active January 7, 2016 06:04
Show Gist options
  • Save kitlangton/622d9a1eb5c4bb6e6db9 to your computer and use it in GitHub Desktop.
Save kitlangton/622d9a1eb5c4bb6e6db9 to your computer and use it in GitHub Desktop.
Bending a two-dimensional array to the left and right to get every diagonal path.
def diagonal_coords(size)
left_array = push_array(size, :left)
right_array = push_array(size, :right)
[left_array, right_array].flatten(1)
end
def push_array(size, direction)
array = Array.new(size) { |x| Array.new(size) { |y| [x,y] }}
size.times do |i|
case direction
when :right then right = size - 1 - left = i
when :left then left = size - 1 - right = i
end
right.times do
array[i].unshift(nil)
end
left.times do
array[i] << nil
end
end
array.transpose.map(&:compact)
end
diagonal_coords(6)
# => [[[0, 0]],
# [[0, 1], [1, 0]],
# [[0, 2], [1, 1], [2, 0]],
# [[0, 3], [1, 2], [2, 1], [3, 0]],
# [[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]],
# [[0, 5], [1, 4], [2, 3], [3, 2], [4, 1], [5, 0]],
# [[1, 5], [2, 4], [3, 3], [4, 2], [5, 1]],
# [[2, 5], [3, 4], [4, 3], [5, 2]],
# [[3, 5], [4, 4], [5, 3]],
# [[4, 5], [5, 4]],
# [[5, 5]],
# [[5, 0]],
# [[4, 0], [5, 1]],
# [[3, 0], [4, 1], [5, 2]],
# [[2, 0], [3, 1], [4, 2], [5, 3]],
# [[1, 0], [2, 1], [3, 2], [4, 3], [5, 4]],
# [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5]],
# [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]],
# [[0, 2], [1, 3], [2, 4], [3, 5]],
# [[0, 3], [1, 4], [2, 5]],
# [[0, 4], [1, 5]],
# [[0, 5]]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment