DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Simple Arrange //JavaScript Function

12.29.2005
| 2916 views |
  • submit to reddit
        <a href="http://jsfromhell.com/array/simple-arrange">

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>


example

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

code

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/simple-arrange [v1.0]

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