Silly programming puzzle
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
#!/usr/bin/env ruby | |
# Given a number x, print a diamond of all numbers from 1 to x^2 in the following format | |
# 2: 3: | |
# 1 1 | |
# 3 2 4 2 | |
# 4 7 5 3 | |
# 8 6 | |
# 9 | |
def num_for num, i, j | |
res = num*i+j*(1-num) | |
if i > num | |
res += (num - 1)*(num - i) | |
end | |
res | |
end | |
def print_diamond num | |
sq_num = num * num | |
longest_len = sq_num.to_s.length | |
line_count = num*2-1 | |
mid_line = line_count / 2 + 1 | |
1.upto(line_count).each do |line| | |
nums_this_line = num - (mid_line - line).abs | |
pre_spaces = (mid_line-line).abs*longest_len | |
nums = [] | |
1.upto(nums_this_line).each do |curr_num| | |
nums << sprintf("%#{(num*num).to_s.length}d", num_for(num, line, curr_num)) | |
end | |
puts " "*(pre_spaces)+nums.join(" "*longest_len) | |
end | |
end | |
print_diamond ARGV[0].to_i if __FILE__ == $0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment