* 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
This commit is contained in:
marcandre 2012-11-06 17:11:06 +00:00
Родитель 55fb13eff9
Коммит 1cb9f27c13
2 изменённых файлов: 37 добавлений и 1 удалений

25
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 */

Просмотреть файл

@ -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