r/programming • • May 08 '15

Five programming problems every Software Engineer should be able to solve in less than 1 hour

https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour
2.5k Upvotes

2.1k comments sorted by

View all comments

Show parent comments

1

u/aZeex2ai May 08 '15

rpermute0(n, r, p, ary0);

Reading the code now, it sounds like the real magic lies in this function.

1

u/aZeex2ai May 08 '15
/*
 * Compute repeated permutations of +r+ elements of the set
 * <code>[0..n-1]</code>.
 *
 * When we have a complete repeated permutation of array indexes, copy the
 * values at those indexes into a new array and yield that array.
 *
 * n: the size of the set
 * r: the number of elements in each permutation
 * p: the array (of size r) that we're filling in
 * values: the Ruby array that holds the actual values to permute
 */
static void
rpermute0(const long n, const long r, long *const p, const VALUE values)
{
    long i = 0, index = 0;

    p[index] = i;
    for (;;) {
        if (++index < r-1) {
            p[index] = i = 0;
            continue;
        }
        for (i = 0; i < n; ++i) {
            p[index] = i;
            if (!yield_indexed_values(values, r, p)) {
                rb_raise(rb_eRuntimeError, "repeated permute reentered");
            }
        }
        do {
            if (index <= 0) return;
        } while ((i = ++p[--index]) >= n);
    }
}