From 1cb9f27c13481594469948ddbca982dd5ae4fad8 Mon Sep 17 00:00:00 2001 From: marcandre Date: Tue, 6 Nov 2012 17:11:06 +0000 Subject: [PATCH] * array.c (rb_ary_permutation): Support for Array#permutation.size [Feature #6636] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@37501 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- array.c | 25 ++++++++++++++++++++++++- test/ruby/test_enumerator.rb | 13 +++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/array.c b/array.c index 2971b9c9a4..83c7e2c825 100644 --- a/array.c +++ b/array.c @@ -4323,6 +4323,29 @@ permute0(long n, long r, long *p, long index, char *used, VALUE values) } } +/* + * Returns the product of from, from-1, ..., from - how_many + 1. + * http://en.wikipedia.org/wiki/Pochhammer_symbol + */ +static VALUE +descending_factorial(long from, long how_many) +{ + VALUE cnt = LONG2FIX(how_many >= 0); + while(how_many-- > 0) { + cnt = rb_funcall(cnt, '*', 1, LONG2FIX(from--)); + } + return cnt; +} + +static VALUE +rb_ary_permutation_size(VALUE ary, VALUE args) +{ + long n = RARRAY_LEN(ary); + long k = (args && (RARRAY_LEN(args) > 0)) ? NUM2LONG(RARRAY_PTR(args)[0]) : n; + + return descending_factorial(n, k); +} + /* * call-seq: * ary.permutation { |p| block } -> ary @@ -4358,7 +4381,7 @@ rb_ary_permutation(int argc, VALUE *argv, VALUE ary) long r, n, i; n = RARRAY_LEN(ary); /* Array length */ - RETURN_ENUMERATOR(ary, argc, argv); /* Return Enumerator if no block */ + RETURN_SIZED_ENUMERATOR(ary, argc, argv, rb_ary_permutation_size); /* Return enumerator if no block */ rb_scan_args(argc, argv, "01", &num); r = NIL_P(num) ? n : NUM2LONG(num); /* Permutation size from argument */ diff --git a/test/ruby/test_enumerator.rb b/test/ruby/test_enumerator.rb index c276455a01..a4222f2ac0 100644 --- a/test/ruby/test_enumerator.rb +++ b/test/ruby/test_enumerator.rb @@ -429,5 +429,18 @@ class TestEnumerator < Test::Unit::TestCase end end + def check_consistency_for_combinatorics(method) + [ [], [:a, :b, :c, :d, :e] ].product([-2, 0, 2, 5, 6]) do |array, arg| + assert_equal array.send(method, arg).to_a.size, array.send(method, arg).size, + "inconsistent size for #{array}.#{method}(#{arg})" + end + end + + def test_size_for_array_combinatorics + check_consistency_for_combinatorics(:permutation) + assert_equal 24, [0, 1, 2, 4].permutation.size + assert_equal 2933197128679486453788761052665610240000000, + (1..42).to_a.permutation(30).size # 1.upto(42).inject(:*) / 1.upto(12).inject(:*) + end end