排列组合类的另类实现

Posted on 2005-09-08 15:28  齐国老兵  阅读(1291)  评论(4编辑  收藏  举报
因为一段程序需要用到排列组合,上网查找现成的c#源代码,结果都是采用递归调用的,我觉得这种方式有一些缺点,所以想能否用其他方法实现。通过观察一个排列组合的结果可以总结出规律来:(过段时间补充),现把已经写好的现成的代码贴出来
 1using System;
 2
 3namespace JJBase.ARITHMETIC
 4{
 5    /// <summary>
 6    /// JJBase 的摘要说明。
 7    /// 函数的功能是返回一个排列组合
 8    /// first date:2005-9-3
 9    /// author:梁俊杰
10    /// </summary>

11    public class Combination
12    {
13        public Combination(){}
14        public string[,] Combin(string[] a,int r)
15            /*传入一个字符串数组,sub是取数组中的字符串的个数
16            阶乘公式:http://blog.blogchina.com/upload/2004-11-04/20041104114227831468.gif 
17            C(n,r)=n!/(r!*(n-r)!)
18            本程序采用的算法是:从左到右取值r个不重复的值,保存r个位置到pos[],其中pos[i]的数值肯定比pos[i+1]小
19            如果pos[i]到达a数组最后位置,则pos[i-1]的数值加1;
20            */

21        {
22            int total=a.Length;
23            string[] oneResult=new string[r];
24            int combins=0;//组合个数
25            combins=Factorial(total)/(Factorial(r)*Factorial(total-r));
26            string[,] result=new string[combins,r];
27            int[] pos=new int[r];
28            for(int i=0;i<r;i++)
29            {
30                pos[i]=i;//初始化位置值
31            }

32            pos[r-1]--;
33            for (int l=0;l<combins;l++)//组合个数已经确定
34            {
35                //判断位置是否合法
36                //说明此时需要进位
37                pos[r-1]++;
38                for(int i=r-1;i>=0;i--)
39                {
40                    int k=r-1-i;
41                    if(pos[i]>=total-k)
42                    {
43                        int x=pos[i-1];
44                        x++;
45                        pos[i-1]=x;
46                        for(int m=i;m<r;m++){x++;pos[m]=x;}
47                    }

48                    else{break;}
49                }

50                //取得正确的位置或者下一个位置
51                //把一个结果存入数组result
52                for (int j=0;j<r;j++)
53                {
54                    result[l,j]=a[pos[j]];
55                }

56            }

57            return result;
58            
59        }
 
60        public int Factorial(int n)
61            //返回阶乘的个数
62//n!=?
63        {    int result=1;
64            for(int i=1;i<=n;i++){result*=i;}
65            return result;
66        }

67    }

68}

Copyright © 2024 齐国老兵
Powered by .NET 8.0 on Kubernetes