Input:
[ [a1,b1,c1], [a2,b2,c2,d,2], [a3,b3], ...]
Output:
[ [a1,a2,a3], [a1,a2,b3], [a1,b2,a3], [a1,b2,b3], [a1,c2,a3], [a1,c2,b3], ... ]
So I need combination of all possible sets (order does not matter). Each output set nth
member is a member of nth
input set. I need efficient algorithm, preferably in javascript.
edit
Well I am trying to solve this.
var input = [ [a,b,c], [a1,b1,c1], [a2,b2] ];
var combinationsNum = _.reduce(input,function(num,set){ return num*set.length; }, 1);
var output = new Array(combinationsNum);
for(var i = 0; i < output.length; ++i) output[i] = [];
for(var s = 0; s < input.length; ++s) {
var set = input[s];
for(var m = 0; m < set.length; ++m) {
var memeber = set[m];
// now I need to calculate to which output arrays I have to push this member
}
}
// result should be
// a a1 a2
// a b1 b2
// a c1 a2
// a a1 b2
// a b1 a2
// a c1 b2
// b a1 a2
// b b1 b2
// b c1 a2
// b a1 b2
// b b1 a2
// b c1 b2
// c a1 a2
// c b1 b2
// c c1 a2
// c a1 b2
// c b1 a2
// c c1 b2
As you can see on each set
I have to push each of its members to each output array with some interval and times... I have problem of calculating this...
The fastest method I found in this duplicate question is:
function(arg) {
var r = [], max = arg.length-1;
function helper(arr, i) {
for (var j=0, l=arg[i].length; j<l; j++) {
var a = arr.slice(0); // clone arr
a.push(arg[i][j])
if (i==max) {
r.push(a);
} else
helper(a, i+1);
}
}
helper([], 0);
return r;
};