Skip to content

Instantly share code, notes, and snippets.

@ulitiy
Last active December 10, 2015 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ulitiy/4389722 to your computer and use it in GitHub Desktop.
Save ulitiy/4389722 to your computer and use it in GitHub Desktop.
class Fixnum
def digit_count
(self == 0) ? 1 : Math.log10(self).to_i + 1
end
end
def make_square n
height = Math.sqrt(n)
throw "Input incorrect" unless height == height.to_i
x = ((height - 1) / 2).floor
y = ((height - 1)/2).ceil
height = height.to_i
direction = 0
mat = []
(0 .. n - 1).each do |i|
mat[y]= [] if mat[y].nil?
mat[y][x]= i + 1
case direction
when 0 then x += 1; direction = 1 if x == height - 1 || mat[y - 1].nil? || mat[y - 1][x].nil?
when 1 then y -= 1; direction = 2 if y == 0 || mat[y].nil? || mat[y][x - 1].nil?
when 2 then x -= 1; direction = 3 if x == 0 || mat[y + 1].nil? || mat[y + 1][x].nil?
when 3 then y += 1; direction = 0 if y == height - 1 || mat[y].nil? || mat[y][x + 1].nil?
end
end
print_square mat, n
end
def print_square mat, n
spaces = n.digit_count + 1
for arr in mat
for i in arr
print i.to_s+(" " * (spaces - i.digit_count))
end
print "\n"
end
end
make_square 25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment