Skip to content

Instantly share code, notes, and snippets.

@wmoxam
Created November 21, 2012 20:58
Show Gist options
  • Save wmoxam/4127672 to your computer and use it in GitHub Desktop.
Save wmoxam/4127672 to your computer and use it in GitHub Desktop.
Spiral Fun
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
grid.reverse_each do |row|
row << num
num += 1
end
new_row = []
root.times do
new_row.unshift num
num += 1
end
grid.unshift new_row
else
grid.each do |row|
row.unshift num
num += 1
end
new_row = []
root.times do
new_row << num
num += 1
end
grid << new_row
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