博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

js 组合

Posted on 2009-06-08 13:32  linFen  阅读(930)  评论(1编辑  收藏  举报

 /***
    alist :原来的要排练的数组,n组合的个数
    */
    function getCom(aList, n) {
        var a = []; //新的组合数组
        var count = 0;
        var m = aList.length;
        var flags = [];
        /*初始化*/
        for (var i = 0; i < n; i++) {
            flags[i] = 1;
        }
        for (var i = n; i < m; i++) {
            flags[i] = 0;
        }

        /*第一个组合数*/
        var tempA = [];
        for (var i = 0; i < flags.length; i++) {
            if (flags[i] == 1) {
                tempA.push(aList[i]);
            }

        }

        a.push(tempA.toString());
        count = 1;
        var has10 = false; //是否有"10"组合的标志:true-有;false-无
        var bound = 0; //第一个"10"组合的索引
        var num1 = 0;           //"10"组合左边的"1"的个数
        var j;

        while (true) {
            num1 = 0;
            has10 = false;
            for (var i = 0; i < m - 1; i++) {
                if (flags[i] == 1 && flags[i + 1] == 0)//找到第一个"10"组合
                {

                    bound = i;
                    flags[i] = 0; //将该"10"组合变为"01"组合
                    flags[i + 1] = 1;
                    for (j = 0; j < num1; j++)//将其左边的所有"1"全部移动到数组的最左端
                    {
                        flags[j] = 1;
                    }

                    for (j = num1; j < bound; j++) {
                        flags[j] = 0;
                    }
                    has10 = true;
                    break;

                }

                else if (flags[i] == 1) {
                    num1++;
                }
            }
            if (has10 == false)//没有"10"组合了,代表组合计算完毕
            {
                break;
            }
            else {
                count++;
            }

            /*第count个组合数*/
            tempA = [];
            for (var i = 0; i < flags.length; i++) {
                if (flags[i] == 1) {
                    tempA.push(aList[i]);
                }
            }
            a.push(tempA.toString());

        }
        return a;
    }