Skip to content

Instantly share code, notes, and snippets.

@ajuckel
Created March 28, 2013 14:04
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ajuckel/5263363 to your computer and use it in GitHub Desktop.
Silly programming puzzle
#!/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