Created
March 29, 2024 14:34
-
-
Save mikedll/1f6604b2c7d5677cf3c886319c8d038c to your computer and use it in GitHub Desktop.
Binomial Coefficients by Dynamic Programming, Using Ruby
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 Table | |
def initialize(n, firstValue) | |
@m = {} | |
(0...n).each do |i| | |
@m[i] = {} | |
(0...n).each do |j| | |
@m[i][j] = firstValue | |
end | |
end | |
end | |
def gs(i,j, v = nil) | |
raise "#{i} #{j}" if @m[i].nil? | |
if v | |
@m[i][j] = v | |
else | |
@m[i][j] | |
end | |
end | |
end | |
# | |
# (n k) where | |
# | |
def binomial_coefficient(n, k, show_triangle = false) | |
raise "n cannot be greater than 100 for this solution" if n >= 100 | |
raise "k cannot be greater than n" if k > n | |
return 1 if (n == 0 || k == n) | |
t = Table.new(n+1, 0) | |
(0...(n+1)).each { |i| t.gs(i,0,1) } | |
(1...(n+1)).each { |ij| t.gs(ij,ij,1) } | |
(1...(n+1)).each do |i| | |
(1...i).each do |j| | |
t.gs(i,j,t.gs(i-1,j-1) + t.gs(i-1,j)) | |
end | |
end | |
(0...(n+1)).each { |i| puts (0..i).map { |j| t.get(i,j) }.join(' ') } if show_triangle | |
t.gs(n,k) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment