Created
July 12, 2016 11:42
-
-
Save Tuhaj/6f03562767fdbc02765eeffdbe31e089 to your computer and use it in GitHub Desktop.
simple method to count binomial coefficients https://en.wikipedia.org/wiki/Binomial_coefficient
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
module Probability | |
def binomial(n, k) | |
return 1 if k == 0 || n == k | |
if n < 0 || k < 0 | |
raise ArgumentError, 'both arguments must be greater than 0' | |
elsif k >= n | |
raise ArgumentError, 'second argument can\'t be greater than first one' | |
end | |
( 1+n-k..n ).inject(:*) / (1..k).inject(:*) | |
end | |
end | |
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
require_relative 'binomial' | |
describe Probability do | |
let(:dummy_class) do | |
Class.new { extend Probability} | |
end | |
let(:subject) {dummy_class} | |
it 'binominal gives correct answers' do | |
expect(subject.binomial(8,4)).to eql 70 | |
expect(subject.binomial(5,2)).to eql 10 | |
expect(subject.binomial(5,3)).to eql 10 | |
end | |
it 'binominal returns 1 if both exponents are the same' do | |
expect(subject.binomial(3,3)).to eql 1 | |
end | |
it 'binominal returns 1 if both the second exponent is equal to 0' do | |
expect(subject.binomial(7,0)).to eql 1 | |
end | |
context 'binominal raises errors' do | |
it 'for wrong order of arguments' do | |
expect { subject.binomial(1,2) }.to raise_error(ArgumentError) | |
end | |
it 'for negative numbers in arguments ' do | |
expect { subject.binomial(-1,-2) }.to raise_error(ArgumentError) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment