Some simple additions to Integer for combinatorics purposes. Will calculate the number of possibilities in an “n choose m” scenario (no repetitions). Adds factorial because that is required for the calculation.
Usage:
irb(main):001:0> require 'combinatorics' => true irb(main):002:0> 3.fact => 6 irb(main):003:0> 10.fact => 3628800 irb(main):004:0> 100.fact => 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 irb(main):005:0> 3.choose(2) => 3 irb(main):006:0> 6.choose(2) => 15 irb(main):007:0> 100.choose(7) => 16007560800 irb(main):008:0> 10000.choose(27) => 88666586562493644592361321224866562980818106140387273533229708768701222758880000
Code:
class Integer def choose(m) return (self.fact / (m.fact * (self - m).fact)) end def fact (2..self).inject(1) { |f, n| f * n } end end