Created
October 26, 2018 10:01
-
-
Save zerobias/6116d2807aa496dc242469eef0860741 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
const generatePermutations = (items, process) => { | |
const mutableItems = items.slice(); | |
const isEven = n => (n & 1) === 0; | |
const permute = (itemArray, x, last) => { | |
if (isEven(last)) { x = 0; } | |
const temp = itemArray[x]; | |
itemArray[x] = itemArray[last]; | |
itemArray[last] = temp; | |
}; | |
const generate = function generateNext(last, process) { | |
let i; | |
if (last === 0) { | |
process(mutableItems); | |
} | |
else { | |
for (i = 0; i < last; i += 1) { | |
generateNext(last - 1, process); | |
permute(mutableItems, i, last); | |
} | |
generateNext(last - 1, process); | |
} | |
}; | |
generate(mutableItems.length - 1, process); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment