Skip to content

Instantly share code, notes, and snippets.

@mandiwise
Last active June 10, 2020 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mandiwise/03f924a19c076e2525fd3e33f27b9e5d to your computer and use it in GitHub Desktop.
Save mandiwise/03f924a19c076e2525fd3e33f27b9e5d to your computer and use it in GitHub Desktop.
Get all unique permutations of character strings in an array.
let someChars = ['A', 'B', 'C', 'D'];
/**
* Handle all permutations for one array item (in relation to all other array items)
*/
function permutateAgainstOneItem(arr) {
let [first, ...tail] = arr;
let head = [first];
let permutations = [];
const reduceTail = function () {
return tail.reduce((acc, char, i) => {
// fix the char to the left
head.push(char);
tail.splice(i, 1);
// console.log(head, tail);
// only push to the permutation array if we've arrived recursively
// at the end of the tail array (so no dupes!)
if (tail.length === 1) acc.push([...head, ...tail].join(''));
// reduce recursively as long as the tail more than one item left
if (tail.length > 1) reduceTail();
// as you were...
head.pop();
tail.splice(i, 0, char);
return acc;
}, permutations);
}
reduceTail(arr);
return permutations;
}
/**
* Produces all char permutations for all items in the array
*/
function permutateArray(chars) {
const allPermutations = chars.reduce((acc, curr, i, arr) => {
const charPermutations = permutateAgainstOneItem(arr);
acc.push(...charPermutations);
// take first item off the arr and move it to the back
const first = arr.shift();
arr.push(first);
return acc;
}, []);
// Remove dupes!
return [...new Set(allPermutations)];
}
console.log(permutateArray(someChars));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment