HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

`r` permutations of `n`

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
permutationsstackoverflowprogramming

Problem

I have written this snippet to find r-permutations of n, i.e. if I have an array of n=3 {0,1,2}, then r=2 permutations will be {{0, 1}, {0, 2}, {1, 0}, {1, 2}, {2, 0}, {2, 1}}.
Can somebody review it and help me optimize / reduce its complexity (I don't want to use recursive function):

"_getAllPermutation": function(input, allPermutations, usedIndices, r) {
    var index = 0,
        usedIndex = null;

    for (; index  0) {
            this._getAllPermutation(input, allPermutations, usedIndices, r);
        }
        input.splice(index, 0, usedIndex);
        r++;
        usedIndices.pop();
    }
}

Solution

I know you asked for a non-recursive version, but recursion is a natural way to approach this problem. Here's a compact, though not high-performance, approach:

function nPr(xs, r) {
    if (!r) return [];
    return xs.reduce(function(memo, cur, i) {
        var others  = xs.slice(0,i).concat(xs.slice(i+1)),
            perms   = nPr(others, r-1),
            newElms = !perms.length ? [[cur]] :
                      perms.map(function(perm) { return [cur].concat(perm) });
        return memo.concat(newElms);
    }, []);
}


All we're doing is taking each element, and then appending it to the (r-1) permutations of all the other elements.

It is possible to do this using while and without recursion, though it will be hard to make that approach as terse. I'll try to take a shot at it later.

Code Snippets

function nPr(xs, r) {
    if (!r) return [];
    return xs.reduce(function(memo, cur, i) {
        var others  = xs.slice(0,i).concat(xs.slice(i+1)),
            perms   = nPr(others, r-1),
            newElms = !perms.length ? [[cur]] :
                      perms.map(function(perm) { return [cur].concat(perm) });
        return memo.concat(newElms);
    }, []);
}

Context

StackExchange Code Review Q#111188, answer score: 5

Revisions (0)

No revisions yet.