Simple Permutation //JavaScript Repository

Description

Mathematical permutation on array elements.
Created: 2005.08.08 - Modified 2005.11.28

Code (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/permute [rev. #1]

permute = function(v, m){
    for(var p = -1, j, k, f, r, l = v.length, q = 1, i = l + 1; --i; q *= i);
    for(x = [new Array(l), new Array(l), new Array(l), new Array(l)], j = q, k = l + 1, i = -1;
        ++i < l; x[2][i] = i, x[1][i] = x[0][i] = j /= --k);
    for(r = new Array(q); ++p < q;)
        for(r[p] = new Array(l), i = -1; ++i < l; !--x[1][i] && (x[1][i] = x[0][i],
            x[2][i] = (x[2][i] + 1) % l), r[p][i] = m ? x[3][i] : v[x[3][i]])
            for(x[3][i] = x[2][i], f = 0; !f; f = !f)
                for(j = i; j; x[3][--j] == x[2][i] && (x[3][i] = x[2][i] = (x[2][i] + 1) % l, f = 1));
    return r;
};

Example (Example)

<script type="text/javascript">
//<![CDATA[

var a = ["A", "B", "C", "D"], j = permute(a);
document.write(
    "<h2>", a.join(" - "), " = ", j.length, "</h2>",
    j.join("<br />")
);

//]]>
</script>

Help

permute(vector: Array, [useIndex: Boolean = false]): Array
The function returns a bidimensional array (where line = group and column = element), containing all the possibilities to group the elements without repeat any of them.
vector
array that will be permuted
useIndex
defines the return type, if true, returns just a "map" containing the indexes of the vector argument, otherwise, it uses the values of the array

Rank (Votes: 63)

2.30