Created
November 21, 2012 20:58
-
-
Save wmoxam/4127672 to your computer and use it in GitHub Desktop.
Spiral Fun
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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