Skip to content

Instantly share code, notes, and snippets.

@Paxa
Forked from ulitiy/gist:4389722
Created December 27, 2012 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Paxa/4390042 to your computer and use it in GitHub Desktop.
Save Paxa/4390042 to your computer and use it in GitHub Desktop.
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] ||= []
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)
end
def print_square(mat)
offset = mat.flatten.max.to_s.size + 1
res = mat.map do |coll|
coll.map {|v| "%#{offset}d" % v.to_i }.join(' ')
end.join("\n")
puts res
end
make_square(5 ** 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment