Having followed the discussion of this quiz, I suspect this is going
to look a bit bloated compared to some other solutions, as I took the
simple approach of building up the entire triangle in memory, then
printing it out afterwards. Anyway, here it is:
#!/usr/bin/env ruby
size = ARGV[0].to_i
rows = Array.new(size)
calculate the numbers
rows[0] = [1]
(1…size - 1).each do |n|
rows[n] = Array.new(n)
m = 0
rows[n - 1].inject 0 do |prev, current|
rows[n][m] = prev + current
m += 1
current
end
rows[n] << 1
end
longest number will be in the middle of the bottom row
max_length = rows[size - 1][size/2 - 1].to_s.length
pad, centre and output
padded = rows.collect do |row|
row.inject “” do |line, element|
line + element.to_s.center(max_length + 2)
end
end
width = padded[size - 1].length
padded.each {|row| puts row.center(width)}
Output with 13 rows (the most that’ll fit in 80 characters):
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
That looks wrong in my mail program, but it does all line up nicely
in a monospaced font!
Kerry