how to get distinct permutations of a set in javascript

Here is a recursive approach that uses backtracking to generate all distinct permutations of a set:

index.tsx
function getPermutations(set) {
  const results = [];
  
  // If set is empty, return an empty array
  if (set.length === 0) {
    results.push([]);
    return results;
  }

  // Iterate over each element in the set
  for (let i = 0; i < set.length; i++) {
    // Copy the set without the current element
    const rest = set.slice(0, i).concat(set.slice(i + 1));
    
    // Recursively generate permutations of the rest of the set
    const permutations = getPermutations(rest);
    
    // Add the current element to each of the permutations
    const allPermutations = permutations.map((permutation) => [set[i], ...permutation]);
    
    // Add the new permutations to the results
    results.push(...allPermutations);
  }

  // Return the list of all permutations
  return results;
}
790 chars
28 lines

Here's an example of how to use this function:

index.tsx
const set = [1, 2, 3];
const permutations = getPermutations(set);
console.log(permutations); // [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
146 chars
4 lines

This implementation handles sets of any size and works with any data type, as long as the elements of the set are comparable.

gistlibby LogSnag