Javascript 我需要把所有可能的10个组合从这个数组放到另一个数组中。我从我的代码中得到的只是3种可能的组合
我需要把所有可能的10个组合从这个数组放到另一个数组中。我从我的代码中得到的只是3种可能的组合Javascript 我需要把所有可能的10个组合从这个数组放到另一个数组中。我从我的代码中得到的只是3种可能的组合,javascript,arrays,combinations,Javascript,Arrays,Combinations,我需要把所有可能的10个组合从这个数组放到另一个数组中。我从我的代码中得到的只是3种可能的组合 let X = ['Me', 'You', 'Her', 'Him', 'Them', 'She', 'juice', 'mango', 'orange', 'pillow', 'clock', 'tyre', 'car', 'calendar', 'fan', 'cloth', 'television', 'laptops', 'Honda', 'remote', 'echo'];
let X = ['Me', 'You', 'Her', 'Him', 'Them', 'She', 'juice', 'mango', 'orange', 'pillow', 'clock', 'tyre', 'car', 'calendar', 'fan', 'cloth', 'television', 'laptops', 'Honda', 'remote', 'echo'];
function combinations(arr) {
let sets = [];
let length = arr.length;
let firstHalf = arr.slice(0, length/2);
let secondHalf = arr.slice(-length/2);
sets.push(firstHalf, secondHalf);
push(firstHalf, secondHalf, sets);
push(firstHalf, secondHalf, sets);
return [sets, `The number of possible combinations: ${sets.length}`];
}
function push(A, B, arr){
let i=0, j=0, k=1;
while(i+k < A.length){
for(let j=0; j<B.length; j++){
arr.push([A[i], A[i+k], B[j]]);
}
k++;
if(k === 3){
i++;
k=1;
}
}
}
console.log(combinations(X));
我没有正确理解您的问题,但这里是如何找到给定数组的所有可能组合 组合的总数为数组的2^长度。假设没有重复 对于您的阵列,它将是2^21=2097152 常量组合=xs=> xs.reduceacc,x=>[…acc,…acc.mapa=>a.concatx],[] 常数t=组合[1,2,3];
console.logt.length,t;请澄清你所说的组合是什么意思。我们应该选择这些项目中的多少?顺序不重要吗?如果你说你需要从这21个组合中选择10个,那就是352716个组合。这就是你需要的?