Ruby Quiz #84: Pascal’s Triangle
I’ve started getting interested in Ruby Quiz as a way to keep my Ruby-fu sharp, and I think I’m gonna make it a regular feature here.
Today’s quiz question revolves around Pascal’s Triangle.
Here’s my answer, after the fold.
class PascalsTriangle
# Instantiates an n-row Pascal's Triangle.
def initialize(number_of_rows = 5)
@rows = [[1]]
2.upto(number_of_rows) do |i|
row = [1]
1.upto(i-2) do |j|
row << @rows.last[(j-1) % @rows.last.size] + @rows.last[j % @rows.last.size]
end
@rows << (row << 1)
end
end
# Converts the triangle into a centered string display.
def to_s
longest_digit = @rows.flatten.inject(0){ |max, num| num > max ? num : max }.to_s.size
padded_rows = @rows.map{ |row| row.map{ |num| num.to_s.center(longest_digit) }.join(’ ‘) }
longest_row = padded_rows.last.size
padded_rows.map{ |row| row.center(longest_row) }.join(”\\n”)
end
end
puts PascalsTriangle.new(ARGV[0].to_i)
Witness the fitness:
$ ruby pp_pascal.rb 10
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
Yay! Numbers!
June 28th, 2006 at 6:53am
You seem to have an extraneous “/code>” at the end of your code block here.
Also, I try running this in WinXP and here is my result? Any ideas? Font wierdness maybe?
C:\rails\projects\test>ruby pp.rb 10
1 n
1 1 n 1 2 1
n 1 3 3 1 n
1 4 6 4 1 n 1 5 10
10 5 1 n 1 6 15 20 15 6 1
n 1 7 21 35 35 21 7 1 n 1 8 2
8 56 70 56 28 8 1 n 1 9 36 84 126 126 84
36 9 1
June 28th, 2006 at 7:00am
Yeah, WordPress occasionally freaks out on well-formed XHTML. Also, it occasionally freaks out on backslashes, which is why your output has n as in “november” instead of \n as in “newline” in it. I really wish they’d give WordPress a consistent set of text->XHTML rules. *sigh*
Try it now.