Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Calls the block with each repeated permutation of length n of the elements of self; each permutation is an Array; returns self. The order of the permutations is indeterminate.
When a block and a positive Integer argument n are given, calls the block with each n-tuple repeated permutation of the elements of self. The number of permutations is self.size**n.
n = 1:
a = [0, 1, 2]
a.repeated_permutation(1) {|permutation| p permutation }
Output:
[0]
[1]
[2]
n = 2:
a.repeated_permutation(2) {|permutation| p permutation }
Output:
[0, 0]
[0, 1]
[0, 2]
[1, 0]
[1, 1]
[1, 2]
[2, 0]
[2, 1]
[2, 2]
If n is zero, calls the block once with an empty Array.
If n is negative, does not call the block:
a.repeated_permutation(-1) {|permutation| fail 'Cannot happen' }
Returns a new Enumerator if no block given:
a = [0, 1, 2]
a.repeated_permutation(2) # => #<Enumerator: [0, 1, 2]:permutation(2)>
Using Enumerators, it's convenient to show the permutations and counts for some values of n:
e = a.repeated_permutation(0)
e.size # => 1
e.to_a # => [[]]
e = a.repeated_permutation(1)
e.size # => 3
e.to_a # => [[0], [1], [2]]
e = a.repeated_permutation(2)
e.size # => 9
e.to_a # => [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
 
               static VALUE
rb_ary_repeated_permutation(VALUE ary, VALUE num)
{
    long r, n, i;

    n = RARRAY_LEN(ary);                  /* Array length */
    RETURN_SIZED_ENUMERATOR(ary, 1, &num, rb_ary_repeated_permutation_size);      /* Return Enumerator if no block */
    r = NUM2LONG(num);                    /* Permutation size from argument */

    if (r < 0) {
        /* no permutations: yield nothing */
    }
    else if (r == 0) { /* exactly one permutation: the zero-length array */
        rb_yield(rb_ary_new2(0));
    }
    else if (r == 1) { /* this is a special, easy case */
        for (i = 0; i < RARRAY_LEN(ary); i++) {
            rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i)));
        }
    }
    else {             /* this is the general case */
        volatile VALUE t0;
        long *p = ALLOCV_N(long, t0, r);
        VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
        RBASIC_CLEAR_CLASS(ary0);

        rpermute0(n, r, p, ary0); /* compute and yield repeated permutations */
        ALLOCV_END(t0);
        RBASIC_SET_CLASS_RAW(ary0, rb_cArray);
    }
    return ary;
}
            

Was this page useful?