Created
October 1, 2021 04:40
-
-
Save gtchakama/8c1d602a70206f4f4c40073f18f1ca58 to your computer and use it in GitHub Desktop.
Permutations - Generates all permutations of an array's elements (contains duplicates).
This file contains 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 permutations = arr => { | |
if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr; | |
return arr.reduce( | |
(acc, item, i) => | |
acc.concat( | |
permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [ | |
item, | |
...val, | |
]) | |
), | |
[] | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Permutations
Generates all permutations of an array's elements (contains duplicates).