diff options
-rw-r--r-- | array.c | 25 | ||||
-rw-r--r-- | test/ruby/test_enumerator.rb | 13 |
2 files changed, 37 insertions, 1 deletions
@@ -4324,6 +4324,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 * ary.permutation -> Enumerator @@ -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 |