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 13 hours ago by avibootz

Related questions

...