Skip to content

Instantly share code, notes, and snippets.

@craftgear
Last active May 14, 2018 12:30
Show Gist options
  • Save craftgear/20e4edb0f52201897e2134a8b84cc78d to your computer and use it in GitHub Desktop.
Save craftgear/20e4edb0f52201897e2134a8b84cc78d to your computer and use it in GitHub Desktop.
Permutation with recursion
const insertItem = (xs, index, item) => [...xs.slice(0, index), item, ...xs.slice(index)];
const range = number => [...Array(number).keys()];
const permutate = (xs, accum = []) => {
const [head, ...tail] = xs;
if (!head) {
return accum;
}
return accum.length === 0
? permutate(tail, [[head]])
: permutate(
tail,
accum.reduce((tempAccum, arrayValue) => {
const insertPositions = range(arrayValue.length + 1);
const insertHeadIntoArray = insertItem(head)(arrayValue);
return tempAccum.concat(insertPositions.map(insertHeadIntoArray));
}, [])
);
};
console.log(permutate([1, 2, 3]));
/*
[ [ 3, 2, 1 ],
[ 2, 3, 1 ],
[ 2, 1, 3 ],
[ 3, 1, 2 ],
[ 1, 3, 2 ],
[ 1, 2, 3 ] ]
*/
console.log(permutate(['a', 'b', 'c']));
/*
[ [ 'c', 'b', 'a' ],
[ 'b', 'c', 'a' ],
[ 'b', 'a', 'c' ],
[ 'c', 'a', 'b' ],
[ 'a', 'c', 'b' ],
[ 'a', 'b', 'c' ] ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment