Skip to content

Instantly share code, notes, and snippets.

@alancnet
Created July 23, 2015 17:00
Show Gist options
  • Save alancnet/fe6b1e78bc971532c775 to your computer and use it in GitHub Desktop.
Save alancnet/fe6b1e78bc971532c775 to your computer and use it in GitHub Desktop.
function cycle(array) {
function cycleInt(array, count) {
if (count == array.length) return [];
var tmp = array.slice(0);
tmp.push(tmp.shift());
return cycleInt(tmp, count + 1).concat([tmp]);
}
return cycleInt(array, 0);
}
function flatten(col) {
return col.reduce(function(pv, cv) {
return pv.concat(cv);
}, [])
}
function permutations(array) {
if (array.length <= 1) return array;
return flatten(
cycle(array)
.map(function(c) {
return permutations(c.slice(1))
.map(function(p) {
return [c[0]].concat(p);
})
})
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment