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 JavaScript

1 Answer

0 votes
// Generate all permutations recursively
function permutations(arr, l = 0, r = arr.length - 1) {
  if (l === r) {
    console.log(arr.join(" "));
    return;
  }
  for (let i = l; i <= r; i++) {
    [arr[l], arr[i]] = [arr[i], arr[l]]; // swap
    permutations(arr, l + 1, r);
    [arr[l], arr[i]] = [arr[i], arr[l]]; // backtrack
  }
}

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

function main() {
  const input = ["a", "b", "c"];

  console.log("All permutations:");
  permutations([...input]); // use a copy

  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

...