diff options
author | marcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2012-11-06 17:11:06 +0000 |
---|---|---|
committer | marcandre <marcandre@b2dd03c8-39d4-4d8f-98ff-823fe69b080e> | 2012-11-06 17:11:06 +0000 |
commit | 1cb9f27c13481594469948ddbca982dd5ae4fad8 (patch) | |
tree | 45f4c154f3aff0391e13ff2b0087b24ad4273767 /array.c | |
parent | 55fb13eff9dbc5c0565dfb75d6a4e919af00e696 (diff) | |
download | ruby-1cb9f27c13481594469948ddbca982dd5ae4fad8.tar.gz |
* 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
Diffstat (limited to 'array.c')
-rw-r--r-- | array.c | 25 |
1 files changed, 24 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 */ |