Skip to content

Instantly share code, notes, and snippets.

@higuma
Last active September 8, 2023 10:15
Show Gist options
  • Save higuma/9889540 to your computer and use it in GitHub Desktop.
Save higuma/9889540 to your computer and use it in GitHub Desktop.
JavaScript Array permutation generator
// JavaScript Array permutation generator
// (optimized from CoffeeScript output: see ArrayPermutation.coffee)
(function() {
var generatePermutation = function(perm, pre, post, n) {
var elem, i, rest, len;
if (n > 0)
for (i = 0, len = post.length; i < len; ++i) {
rest = post.slice(0);
elem = rest.splice(i, 1);
generatePermutation(perm, pre.concat(elem), rest, n - 1);
}
else
perm.push(pre);
};
/*
extend Array.prototype
e.g. [0, 1, 2].permutation(2)
=> [[0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]]
*/
Array.prototype.permutation = function(n) {
if (n == null) n = this.length;
var perm = [];
generatePermutation(perm, [], this, n);
return perm;
};
})();
@dimasch
Copy link

dimasch commented Jan 14, 2020

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment