how to get all permutations of a set in typescript

To get all the permutations of a set in TypeScript, we can use a recursive algorithm. Here's the code:

index.ts
function getPermutations<T>(arr: T[]): T[][] {
  const result = [];

  if (arr.length === 1) {
    result.push(arr);
    return result;
  }

  for (let i = 0; i < arr.length; i++) {
    const current = arr[i];
    const remaining = [...arr.slice(0, i), ...arr.slice(i + 1)];
    const remainingPermutations = getPermutations(remaining);

    for (let j = 0; j < remainingPermutations.length; j++) {
      result.push([current, ...remainingPermutations[j]]);
    }
  }

  return result;
}
488 chars
21 lines

This function takes an array arr and returns an array of all possible permutations.

The idea behind the algorithm is to take each element in turn, and compute the permutations of the remaining elements recursively. We then combine each of these remaining permutations with the current element to get the permutations for the full set.

We start with the base case where the array contains only one element, in which case there is only one permutation (the array itself).

The function then uses a for loop to iterate over each element of the array, storing the current element in current and computing the remaining elements in remaining. We then recursively compute the permutations for remaining and store the result in remainingPermutations.

We then use another for loop to iterate over each permutation in remainingPermutations, and prepend current to it. We then add each of these new permutations to the result array. When all iterations are complete, we return the result array containing all possible permutations.

gistlibby LogSnag