Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combination without repetition javascript [duplicate]

Given

[
  ["blue", "red"],
  [1, 2],
  [true, false],
]

How can I get the possible combinations in javascript?:

blue, 1, true
blue, 1, false
blue, 2, true
blue, 2, false
red, 1, true
red, 1, false
red, 2, true
red, 2, false

Order doesn't matter.

like image 758
Mauro Aguilar Avatar asked Nov 15 '18 06:11

Mauro Aguilar


1 Answers

this was quite complex, and lots of fun, so thanks for asking!

as here we can have m element arrays of arbitary size,

var a = [
  ["blue", "red"],
  [1, 2],
  [true, false],
]

function allPossibleCombinations(items, isCombination=false){
    // finding all possible combinations of the last 2 items
    // remove those 2, add these combinations
    // isCombination shows if the last element is itself part of the combination series
    if(items.length == 1){
       return items[0]
    }
    else if(items.length == 2){
       var combinations = []
       for (var i=0; i<items[1].length; i++){
           for(var j=0; j<items[0].length; j++){
               if(isCombination){
                   // clone array to not modify original array
                   var combination = items[1][i].slice();
                   combination.push(items[0][j]);
               }
               else{
                   var combination = [items[1][i], items[0][j]];
               }
               combinations.push(combination);
           }
       }
       return combinations
    }
    else if(items.length > 2){
       var last2 = items.slice(-2);
       var butLast2 = items.slice(0, items.length - 2);
       last2 = allPossibleCombinations(last2, isCombination);
       butLast2.push(last2)
       var combinations = butLast2;
       return allPossibleCombinations(combinations, isCombination=true)
    }
}

console.log(allPossibleCombinations(a));
console.log(allPossibleCombinations(a).length);
like image 154
Aditya Shankar Avatar answered Nov 13 '22 22:11

Aditya Shankar