From f5cf7c4e902dcfb67357366966f0d7802b8bda89 Mon Sep 17 00:00:00 2001 From: Run Paint Run Run Date: Mon, 22 Mar 2010 07:29:02 +0000 Subject: [PATCH] Integer#stirling2: Add --- lib/numb/stirling2.rb | 9 +++++++++ spec/numb/stirling2_spec.rb | 23 +++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 lib/numb/stirling2.rb create mode 100644 spec/numb/stirling2_spec.rb diff --git a/lib/numb/stirling2.rb b/lib/numb/stirling2.rb new file mode 100644 index 0000000..48e2d6a --- /dev/null +++ b/lib/numb/stirling2.rb @@ -0,0 +1,9 @@ +# coding: utf-8 +class Integer + def stirling2(m) + n = self + return 1 if (n.zero? and m.zero?) or m == n + return 0 if m > n or m.zero? or n.zero? + (n-1).stirling2(m-1) + m * (n-1).stirling2(m) + end +end diff --git a/spec/numb/stirling2_spec.rb b/spec/numb/stirling2_spec.rb new file mode 100644 index 0000000..8f9e9f2 --- /dev/null +++ b/spec/numb/stirling2_spec.rb @@ -0,0 +1,23 @@ +# coding: utf-8 +describe Integer, "#stirling2" do + @seq = [ + [1], + [1, 1], + [1, 3, 1], + [1, 7, 6, 1], + [1, 15, 25, 10, 1], + [1, 31, 90, 65, 15, 1], + [1, 63, 301, 350, 140, 21, 1], + [1, 127, 966, 1701, 1050, 266, 28, 1], + [1, 255, 3025, 7770, 6951, 2646, 462, 36, 1], + [1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1] + ] + + @seq.to_enum.with_index(1).each do |row, n| + row.to_enum.with_index(1).each do |s, m| + it "returns #{s} as the #{n}#{n.ordinal} Stirling number of the 2nd kind (m = #{m})" do + n.stirling2(m).should == s + end + end + end +end