Skip to content

Instantly share code, notes, and snippets.

@gtchakama
Created October 1, 2021 04:40
Show Gist options
  • Save gtchakama/8c1d602a70206f4f4c40073f18f1ca58 to your computer and use it in GitHub Desktop.
Save gtchakama/8c1d602a70206f4f4c40073f18f1ca58 to your computer and use it in GitHub Desktop.
Permutations - Generates all permutations of an array's elements (contains duplicates).
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,
])
),
[]
);
};
@gtchakama
Copy link
Author

Permutations

Generates all permutations of an array's elements (contains duplicates).

  • Use recursion.
  • For each element in the given array, create all the partial permutations for the rest of its elements.
  • Use Array.prototype.map() to combine the element with each partial permutation, then Array.prototype.reduce() to combine all permutations in one array.
  • Base cases are for Array.prototype.length equal to 2 or 1.
  • ⚠️ WARNING: This function's execution time increases exponentially with each array element. Anything more than 8 to 10 entries may cause your browser to hang as it tries to solve all the different combinations

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment