Arrange //JavaScript Repository

Description

Mathematical arrange (with repetition) on array elements.
Created: 2005.08.08 - Modified 2005.11.29

Code (Download)

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

arrange = function(v, n, m){
    for(var j, k, i = -1, l = v.length, q = Math.pow(l, n), r = new Array(q), c = (new Array(n + 1)).join(0).split(""); ++i < q;)
        for(r[i] = new Array(j = n), k = 1; j--; r[i][j] = m ? c[j] : v[c[j]], k && (++c[j] != l && --k, c[j] %= l));
    return r;
};

Example (Example)

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

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

//]]>
</script>

Help

arrange(vector: Array, n: Integer, [useIndex: Boolean = false]): Array
Do the mathematical arrange (with repetition), groups made up by n elements (n < array size), where the elements are distincted by the order or value. In the arrange with repetition repeated elements can appear in the same group. The function returns a bidimensional array, where line = arrange and column = element.
vector
array that will be arranged
n
amount of elements in each group
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)

1.79