Skip to content

Instantly share code, notes, and snippets.

@scottillogical
Last active December 27, 2015 02:59
Show Gist options
  • Save scottillogical/7256120 to your computer and use it in GitHub Desktop.
Save scottillogical/7256120 to your computer and use it in GitHub Desktop.
Write a function that accepts four arguments. The first two arguments are the size of the grid (h x w), filled with ascending integers from left to right, top to bottom, starting from 1. The next two arguments are is the starting positions, the row (r) and column (c). Return an array of integers obtained by spiraling outward anti-clockwise from …
require 'matrix'
def spiral(height, width, start_row, start_col)
@results = []
i = 0
m = Matrix.build(height, width) do |row, col|
i+=1
end
start_row = x = start_row-1
start_col = y = start_col -1
distance = 1
@max_length = m.row_size * m.column_size
@results << m[x, y]
def store_result(m, x, y)
if @results.length < @max_length and m[x, y] and x >= 0 and y >= 0
@results << m[x, y]
end
end
until(@results.length == @max_length) do
# go up
until(x==(start_row - distance))
x -= 1
store_result(m, x, y)
end
# go left
until(y==(start_col - distance))
y -= 1
store_result(m, x, y)
end
# go down
until(x==(start_row + distance))
x += 1
store_result(m, x, y)
end
# go right"
until(y==(start_col + distance))
y += 1
store_result(m, x, y)
end
distance+=1
end
@results
end
require 'minitest/autorun'
require './spiral'
describe "Spiral" do
it "spirals in a square" do
assert_equal(spiral(5, 5, 3, 3), [13, 8, 7, 12, 17, 18, 19, 14, 9, 4, 3, 2, 1, 6, 11, 16, 21, 22, 23, 24, 25, 20, 15, 10, 5])
end
it "spirals in a non-square rectangle" do
assert_equal(spiral(2, 4, 1, 2), [ 2, 1, 5, 6, 7, 3, 8, 4 ])
end
end
@bogardon
Copy link

bogardon commented Nov 7, 2013

really like this answer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment