Created
July 19, 2012 02:52
-
-
Save barrettclark/3140447 to your computer and use it in GitHub Desktop.
Pascal's Triangle Problem (recursive solution)
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
class PascalTriangle | |
def initialize | |
@digits = [] | |
end | |
def calculate_row(row) | |
row = row.to_f | |
0.upto(row) { |column| @digits << calculate_number(row, column).to_i } | |
@digits | |
end | |
def calculate_number(row, column) | |
r = row + 1 | |
if column == 0 | |
1 | |
else | |
previous = calculate_number(row, column-1) | |
previous * ((r - column) / column) | |
end | |
end | |
end | |
if __FILE__ == $0 | |
row = ARGV[0] || 5 | |
puts "Calculating Pascal's triangle row: #{row}" | |
pc = PascalTriangle.new | |
digits = pc.calculate_row(row) | |
puts digits.join(', ') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Back at the beginning of this year @petesharum and I toyed around with the Pascal's Triangle problem. There was a post on HN. We had different approaches. Mine was slower because recursion is slower. I still liked what I came up with, though.