Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,011 questions

51,958 answers

573 users

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 Nov 21, 2025 by avibootz

Related questions

...