how to get distinct combinations of a set in javascript

Hey there! It seems like you want to generate distinct combinations of elements from a set. No worries, I've got your back. 😊

Given a set of elements, we can use JavaScript to generate all unique combinations of those elements. Here's an iterative approach using a function we'll call getCombinations:

index.tsx
function getCombinations(set, combinationSize) {
  const results = [];
  
  function combine(startIndex, combo) {
    if (combo.length === combinationSize) {
      results.push(Array.from(combo));
      return;
    }
  
    for (let i = startIndex; i < set.length; i++) {
      combo.add(set[i]);
      combine(i + 1, combo);
      combo.delete(set[i]);
    }
  }
  
  combine(0, new Set());
  return results;
}

const exampleSet = [1, 2, 3, 4];
const combinationSize = 3;
const distinctCombinations = getCombinations(exampleSet, combinationSize);
console.log(distinctCombinations);
583 chars
25 lines

This function works by taking two parameters: the input set, from which you wants to generate the combinations, and combinationSize, specifying the size of each combination group.

We call an inner function combine, which does the actual work of generating the combinations through recursion. When the length of the combo set equals the desired combination size, we add a copy of the combo to the results array, continuing until all distinct combinations have been generated.

Finally, the getCombinations returns the results array containing all distinct combinations.

For our example, exampleSet = [1, 2, 3, 4] and combinationSize = 3, the output will be:

index.tsx
[
  [1, 2, 3],
  [1, 2, 4],
  [1, 3, 4],
  [2, 3, 4]
]
55 chars
7 lines

And that's it! You now have distinct combinations of elements from your set. Don't forget to play around with it and have fun creating combinations! 🚀

related categories

gistlibby LogSnag