how to get distinct combinations of a set in javascript

Here is a solution to get distinct combinations of a set in javascript using recursion and memoization:

index.tsx
function getCombinations(set) {
  let memo = {}; // memoization object to store already computed combinations
  function helper(set) {
    let key = set.toString(); // convert set to string for memoization
    if (memo.hasOwnProperty(key)) return memo[key]; // if already computed, return from memo
    let result = [];
    if (set.length == 0) {
      result.push([]); // base case
      return result;
    }
    let first = set[0];
    let rest = set.slice(1);
    let subCombs = helper(rest);
    result = result.concat(subCombs);
    subCombs.forEach(function(subComb) {
      let comb = [first].concat(subComb);
      result.push(comb);
    });
    memo[key] = result; // memoize the result
    return result;
  }
  return helper(set);
}

// Example usage:
let set = [1, 2, 3];
let combs = getCombinations(set);
console.log(combs);
// Output: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
903 chars
30 lines

In this solution, we use recursion to break down the set into smaller subsets and combine the results to get all the distinct combinations. We also use memoization to store already computed results and avoid recomputation.

gistlibby LogSnag