Skip to content

Instantly share code, notes, and snippets.

@foucist
Forked from wmoxam/gist:4127672
Created November 21, 2012 21:40
Show Gist options
  • Save foucist/4127990 to your computer and use it in GitHub Desktop.
Save foucist/4127990 to your computer and use it in GitHub Desktop.
Spiral Fun - slight refactoring
def method(grid,root,rev = false)
grid.send(rev ? :reverse_each : :each) do |row|
row.send(rev ? :<< : :unshift, @num)
@num += 1
end
new_row = []
root.times do
new_row.send(rev ? :unshift : :<<, @num)
@num += 1
end
grid.send(rev ? :unshift : :<<, new_row)
end
def spiral(root)
return [1] if root == 1
return [[4,3],[1,2]] if root == 2
grid = spiral(root - 1)
@num = (root - 1) ** 2 + 1
if root % 2 == 0
method(grid,root)
else
method(grid,root,true)
end
grid
end
input = ARGV.shift
value = input.to_i
root = Math.sqrt(value).to_i
if input && (root ** 2 == value)
grid = spiral(root)
char_length = value.to_s.length
grid.each do |row|
row.each {|i| print "%#{char_length}d " % i }
puts
end
else
puts "Please provide an integer value for a perfect square"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment