Skip to content

Instantly share code, notes, and snippets.

@barrettclark
Created July 19, 2012 02:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barrettclark/3140447 to your computer and use it in GitHub Desktop.
Save barrettclark/3140447 to your computer and use it in GitHub Desktop.
Pascal's Triangle Problem (recursive solution)
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
@barrettclark
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment