instance method
Array#repeated_combination
(::int n) { (::Array[Elem] c) -> void } -> self
(::int n) -> ::Enumerator[::Array[Elem], self]
repeated_combination(size) {|combination| ... } → self
repeated_combination(size) → new_enumerator
array.c
View on GitHub ↗
static VALUE
rb_ary_repeated_combination(VALUE ary, VALUE num)
{
long n, i, len;
n = NUM2LONG(num); /* Combination size from argument */
RETURN_SIZED_ENUMERATOR(ary, 1, &num, rb_ary_repeated_combination_size); /* Return enumerator if no block */
len = RARRAY_LEN(ary);
if (n < 0) {
/* yield nothing */
}
else if (n == 0) {
rb_yield(rb_ary_new2(0));
}
else if (n == 1) {
for (i = 0; i < RARRAY_LEN(ary); i++) {
rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i)));
}
}
else if (len == 0) {
/* yield nothing */
}
else {
volatile VALUE t0;
long *p = ALLOCV_N(long, t0, n);
VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
RBASIC_CLEAR_CLASS(ary0);
rcombinate0(len, n, p, n, ary0); /* compute and yield repeated combinations */
ALLOCV_END(t0);
RBASIC_SET_CLASS_RAW(ary0, rb_cArray);
}
return ary;
}
With a block given, calls the block with each repeated combination of length size of the elements of self; each combination is an array; returns self. The order of the combinations is indeterminate.
If a positive integer argument size is given, calls the block with each size-tuple repeated combination of the elements of self. The number of combinations is (size+1)(size+2)/2.
Examples:
-
sizeis 1:Examplec = [] [0, 1, 2].repeated_combination(1) {|combination| c.push(combination) } c # => [[0], [1], [2]]
-
sizeis 2:Examplec = [] [0, 1, 2].repeated_combination(2) {|combination| c.push(combination) } c # => [[0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2]]
If size is zero, calls the block once with an empty array.
If size is negative, does not call the block:
Example
[0, 1, 2].repeated_combination(-1) {|combination| fail 'Cannot happen' }
With no block given, returns a new Enumerator.
Related: see Methods for Combining.