Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

JS从数组M中取出N个元素的所有组合

数组 M = [1,2,3,4....]
从里面取N个项组合不重复
例如取两个为
1,2
1,3
1,4
2,3
2,4
3,4
取三个
1,2,3
1,2,4
2,3,4


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

一个可用的实现(递归实现):

xrt=[];
function combine_increase( iArr , start, rt, count , NUM, arr_len){ // 从有arr_len个元素的数组中抽取NUM个元素的组合所有可能
    let i = 0;
    for(let i=start; i<arr_len+1-count; i++){
        rt[count - 1]=i;
        if( count -1 == 0){
            let tmp=[];
            for(let j=NUM-1;j>=0;j--){
                tmp.push(arr[rt[j]]);
            }
            xrt.push(tmp);
        }else{
            combine_increase( iArr , i+1 , rt, count -1 , NUM, arr_len);
        }
    }
}

let arr=[1,2,3,4,5,6,7,8,9,10];
var rt=new Array(4)
combine_increase(arr, 0, rt, 6, 6, 10);
console.log(xrt)

另外一个实现(非递归的):

const M_FILL = 0; // 填充模式
const M_INC = 1;  // 递增模式
function getArr(idx_arr,eArr,m){
    var rt=[];
    for(let i=0;i<m;i++){
        rt.push( eArr[idx_arr[i]])
    }
    return rt;
}

function IterativeCombos( n,  m,  idx_arr,  eArr ){// 从有n个元素的数组中抽取m个元素的的所有可能情况
    var rt=[];
    let mode=M_FILL;
    let i = 0;
    while( i>=0 ){
        if (mode == M_FILL) { 
            if(i==0){
                idx_arr[0]=0;
            }else{
                idx_arr[i]=idx_arr[i-1]+1;
            }
            if (i == m-1){
                rt.push( getArr(idx_arr,eArr,m));
                mode = M_INC;
            }else{
                i++;
            }
        }else{
            idx_arr[i]++;
            if( idx_arr[i]>n-m+i){
                i--;
            }else{
                if(i==m-1){
                    rt.push( getArr(idx_arr,eArr,m));
                }else{
                    i++;
                    mode=M_FILL;
                }
            }
        }
    }
    return rt;
}

console.log( IterativeCombos(10,4,idx_arr,arr )   )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...