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

C#组合算法 (2)

Posted on 2009-06-08 13:29  linFen  阅读(704)  评论(0编辑  收藏  举报

   public static List<string> GetCom<T>(T[] aConde,int n)
       {
        List<string > list = new List<string>();
        int m =aConde.Length;
        int[] flags = new int[m];
        for (int i = 0; i < n; i++)
        {
            flags[i] = 1;
        }

        for (int i = n; i < m; i++)
        {
            flags[i] = 0;
        }

     
       string s = "";
        for (int i = 0; i < flags.Length; i++)
        {
            if (flags[i] == 1)
            {
             
                s += aConde[i].ToString()+",";
            }
         
        }
        if(s.Length>0 && s.EndsWith(","))
        {
               s=s.Substring(0,s.Length-1);
        }
        list.Add(s);
     

    
        int count = 1;

        bool has10 = false; //是否有"10"组合的标志:true-有;false-无

        int bound = 0; //第一个"10"组合的索引

        int num1 = 0;           //"10"组合左边的"1"的个数
        int j;

        while (true)
        {
            num1 = 0;

            has10 = false;


            for (int 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++;
            }
            s = "";
            for (int i = 0; i < flags.Length; i++)
            {
                if (flags[i] == 1)
                {

                    s += aConde[i].ToString() + ",";
                }

            }
            if (s.Length > 0 && s.EndsWith(","))
            {
                s = s.Substring(0, s.Length - 1);
            }
            list.Add(s);
        }
        return list;
    }