i'm currently stuck on this problem,
suppose there is an array arr4(length is not fixed). I need to find all combinations of its element.
expected output is:
4-16D-5d
4-16D-5e
4A-16D-5d
4A-16D-5e
4B-16D-5d
4B-16D-5e
4-15D-5d
4-15D-5e
4A-15D-5d
4A-15D-5e
4B-15D-5d
4B-15D-5e
What i tried is:
arr4=[['4','4A','4B'],['16D','15D'],['5d','5e']]; //may contains more elements
alert("arr4 "+arr4);
for(var k=0;k<arr4.length;k++){
alert("k "+k);
arr_v=arr4[k]
alert("arrv"+arr_v);
alert ("arrv lengt"+arr_v.length);
for(var z=0;z<arr_v.length;z++){
m=1;
while(m<arr4.length){
var test=arr4[m];
for(var n=0;n<test.length;n++)
alert(arr_v[z]+"<TEST>"+test[n]);
}
m++;
}
}
I kind of found a solution:
function product() {
return Array.prototype.reduce.call(arguments, function(as, bs) {
return [a.concat(b) for each (a in as) for each (b in bs)]
}, [[]]);
}
BUT
arr4=[['4','4A','4B'],['16D','15D'],['5d','5e']];
alert(product(['4','4A','4B'],['16D','15D'],['5d','5e']);
The above works but the following don't work:
arr4=[['4','4A','4B'],['16D','15D'],['5d','5e']];
alert(product(arr4);
Anyone please suggest a solution
edit:solution here
-
thanks for that formatting, Kolinkmtyson– mtyson2012年02月21日 19:54:17 +00:00Commented Feb 21, 2012 at 19:54
2 Answers 2
You can compute the cartesian product of each sub-array. See this question and its answer
I tried it out, and since it goes off the length of each array, it should work no matter how many elements are in each list and return you a list of each product.
3 Comments
var arr4 = [['4','4A','4B'],['16D','15D'],['5d','5e']];
for(var a = 0; a < arr4[1].length; a++){
if(a != 0){
document.write('<br /><br />');
}
for(var b = 0; b < arr4[0].length; b++){
for(var c = 0; c < arr4[2].length; c++){
document.write(arr4[0][b] + '-' + arr4[1][a] + '-' + arr4[2][c] + '<br />')
}
}
}
Obviously you don't want to use document.write but inside the last for loop is where each lines output will be using
arr4[0][b] + '-' + arr4[1][a] + '-' + arr4[2][b]
jsFiddle for those interested http://jsfiddle.net/5AmMU/1/