How to generate all possible permutations and combinations of an array of chars in TypeScript

1 Answer

0 votes
// Swap two elements in an array
function swap<T>(arr: T[], i: number, j: number): void {
  [arr[i], arr[j]] = [arr[j], arr[i]];
}

// Print array of chars
function printArray(arr: string[]): void {
  console.log(arr.join(" "));
}

// Recursive function to generate permutations
function permute(arr: string[], l: number, r: number): void {
  if (l === r) {
    printArray(arr);
    return;
  }
  for (let i = l; i <= r; i++) {
    swap(arr, l, i);
    permute(arr, l + 1, r);
    swap(arr, l, i); // backtrack
  }
}

// Generate all combinations using bitmask
function generateCombinations(arr: string[]): void {
  const size = arr.length;
  for (let mask = 1; mask < (1 << size); mask++) {
    const combo: string[] = [];
    for (let i = 0; i < size; i++) {
      if (mask & (1 << i)) {
        combo.push(arr[i]);
      }
    }
    console.log(combo.join(" "));
  }
}

function main(): void {
  const input = ["a", "b", "c"];
  const size = input.length;

  console.log("All permutations:");
  permute([...input], 0, size - 1);

  console.log("\nAll combinations:");
  generateCombinations(input);
}

main();




/*
run:

"All permutations:" 
"a b c" 
"a c b" 
"b a c" 
"b c a" 
"c b a" 
"c a b" 
"
All combinations:" 
"a" 
"b" 
"a b" 
"c" 
"a c" 
"b c" 
"a b c" 

*/

 



answered 13 hours ago by avibootz

Related questions

...