0

I'm having trouble finding a solution to a combinatronics problem while making a card game in javascript. I'd like to get all combinations of a set such that all elements are used.

given: [1, 2, 3]
returns: [
    [[1], [2], [3]],
    [[1, 2], 3],
    [[1, 3], 2],
    [[2, 3], 1],
    [[1, 2, 3]]
]

the game is Cassino.

okwme
  • 740
  • 1
  • 7
  • 19
  • Does this answer your question? [Find all possible subset combos in an array?](https://stackoverflow.com/questions/5752002/find-all-possible-subset-combos-in-an-array) – AncientSwordRage Jan 22 '22 at 10:21

2 Answers2

0
 function permute(arr){
   const res = [];
   for(var map = 1; map < 2 ** arr.length; map++){
     const rest = [],
           subset = arr.filter((el, i) => (map & (1 << i)) || (rest.push(el), false));
     //console.log(subset, rest);
     res.push(...(rest.length ? permute(rest).map(arr => [subset,...arr]) : [[subset]]));
   }
   //console.log(res);
   return res;
 }

 console.log(permute([1,2,3]))

Try it!

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • this is much closer to the solution actually. It has redundant results because for me the order doesn't matter, but it includes all the correct subset combinations. maybe it's easier for me to just filter out the repeats from this though, thank you! – okwme Dec 26 '17 at 13:19
-1

This problem can be solved in a recursive manner.

First we need to declare two arrays, one which will contains the input (the given array) and the other will contains the result (initially empty)

var givenArray = [1, 2, 3];
var resultArray = [];

Now let's create our recursive function that will push a subset array to our result array:

function getSubArray(array, position) {
    if(position === givenArray.length) {
        resultArray.push(array);
        return;
    }
    getSubArray(array.concat(givenArray[position]), position+1);
    getSubArray(array, position+1);
}

Now to start set all the subsets to the resultArray we just need to call our getSubArray function with an empty array and a start position which is 0 as arguments

getSubArray([], 0);

After that just remove the last element of the resultArray if you want to remove the empty set ([]) from the result resultArray.splice(-1,1);

You can test the algorithm online via this link: https://jsbin.com/xigipihebe/edit?js,console

Atef
  • 1,294
  • 1
  • 14
  • 27
  • 1
    this is a nice implementation of unordered permutations but it's not what i'm looking for. In my scenario I need to enumerate through those permutations and find all possible combos of them that use all elements from the original array. your given array `var givenArray = [1, 2, 3];` returns `[[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3]]`. i'm looking for a result like `[ [[1], [2], [3]], [[1, 2], 3], [[1, 3], 2], [[2, 3], 1], [[1, 2, 3]]]` – okwme Dec 26 '17 at 13:16