//the faster implementation by japanfever E3839EE383AAE382AAE9B3A9E38388E383ACE383AD
function getPermutations(a) {
var p = [];
var c = a.map(_ => 0);
var i = 0, tmp;
p.push(a.slice());
while (i < a.length) {
if (c[i] < i) {
if (i % 2 === 0) {
tmp = a[0]; a[0] = a[i];
} else {
tmp = a[c[i]]; a[c[i]] = a[i];
}
a[i] = tmp;
p.push(a.slice());
c[i] += 1;
i = 0;
} else {
c[i] = 0;
i += 1;
}
}
return p;
}
Génesis says:
Ok, yours is faster but mine is shorter and more readable 😉
//the faster implementation by japanfever E3839EE383AAE382AAE9B3A9E38388E383ACE383AD
function getPermutations(a) {
var p = [];
var c = a.map(_ => 0);
var i = 0, tmp;
p.push(a.slice());
while (i < a.length) {
if (c[i] < i) {
if (i % 2 === 0) {
tmp = a[0]; a[0] = a[i];
} else {
tmp = a[c[i]]; a[c[i]] = a[i];
}
a[i] = tmp;
p.push(a.slice());
c[i] += 1;
i = 0;
} else {
c[i] = 0;
i += 1;
}
}
return p;
}
Ok, yours is faster but mine is shorter and more readable 😉
http://jsben.ch/BG1iM
near four times faster! hahaha
I’ve checked it, cool benchmark!