-
-
Save Paxa/4390042 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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