For example,
[1,2,3,4], [5], [7,8], [9]
Generate a one-dimensional array, which should be 8 types.
In fact, it looks like a branch ~
[1,5,7,9],
[2,5,7,9],
[1,5,7,9],
/***
** Omitted ...
***/
[4,5,8,9]
What if there is one more element?
[1,2,3,4], [5,6], [7,8], [9]
How to list all possible combinations?
阿神2017-05-16 13:06:38
#这就是求笛卡尔积
from itertools import product
print list(product([1,2,3,4], [5, 6], [7,8], [9]))
phpcn_u15822017-05-16 13:06:38
4*2*2, 16 kinds.
Permutations and combinations, since each array must have one element, then for
array 1: c(4,1)=4,
array 2: c(2,1) =2,
Array 3: c(2,1)=2,
Array 4: c(1,1)=1,
Multiply each one again and pay attention to repeated elements.
阿神2017-05-16 13:06:38
$a1 = array(1,2,3,4);
$a2 = array(5);
$a3 = array(7,8);
$a4 = array(9);
foreach ($a1 as $k1=>$v1){
foreach ($a2 as $k2=>$v2){
foreach ($a3 as $k3=>$v3){
foreach ($a4 as $k4=>$v4){
$a = array($v1,$v2,$v3,$v4);
print_r($a);
echo "<br>";
}
}
}
}
伊谢尔伦2017-05-16 13:06:38
Generally speaking, if there are several groups, several loops are needed. Just combine the elements inside one by one. This is the conventional solution of js. I don’t know if there is a better one.
var a = [1,2,3,4],
b = [5,6],
c = [7,8],
d = [9];
for(var i = 0; i < a.length; i++) {
for(var j = 0; j < b.length; j++) {
for(var k = 0; k < c.length; k++) {
for(var l = 0; l < d.length; l++) {
console.log(a[i] + '-' + b[j] + '-' + c[k] + '-' + d[l]);
}
}
}
}
为情所困2017-05-16 13:06:38
function list(arr){
function newArr(arr){
var num=1;
arr.forEach((x)=>{
num*=x.length
})
var tem=[]
for(var i=0;i<num;i++){
tem[i]=[];
}
return tem
}
function numFn(num){
var pp=[];
var nums=list.length;
arr.forEach(function(x){
nums=nums/x.length
pp.push(x[nums==1?num%x.length:parseInt(num/nums)%x.length]);
})
return pp
}
var list=newArr(arr);
for(var j=0;j<list.length;j++){
list[j]=numFn(j)
}
return list
}