Created
July 23, 2015 17:00
-
-
Save alancnet/fe6b1e78bc971532c775 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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