c#排列组合算法

Combinatorics.cs代码清单

usingSystem;
usingSystem.Collections;
usingSystem.Data;

///<summary>
///组合数学函数集
///</summary>
publicclassCombinatorics
{
#region公共函数


///<summary>
///把二维整形数组转换为数据表
///</summary>
publicstaticDataTableTwoDemisionIntArrayToDataTable(int[,]source)
{
DataTabledt=newDataTable();
DataRowdr;
inti,j;

intb1=source.GetUpperBound(0),b2=source.GetUpperBound(1);//获取二维表的各维长度

for(i=0;i<=b1;i++)//以第二维长度创建数据表的各字段
dt.Columns.Add(i.ToString(),System.Type.GetType("System.Int32"));

for(i=0;i<=b2;i++)//对各返回排列循环
{
dr=dt.NewRow();//准备插入新行
for(j=0;j<=b1;j++)//在新行中逐个填入返回排列的各元素次序
dr[j.ToString()]=source[j,i];//用序数指针获取原元素的值
dt.Rows.Add(dr);//插入新行
}

returndt;
}

///<summary>
///连乘积函数
///</summary>
publicstaticintProduct(intstart,intfinish)
{
intfactorial=1;
for(inti=start;i<=finish;i++)
factorial*=i;
returnfactorial;
}

///<summary>
///阶乘函数
///</summary>
publicstaticintFactorial(intn)
{
returnProduct(2,n);
}

///<summary>
///排列数函数
///</summary>
publicstaticintArrangeCount(intm,intn)
{
returnProduct(n-m+1,n);
}

///<summary>
///生成排列表函数
///</summary>
publicstaticint[,]Arrange(intm,intn)
{
intA=ArrangeCount(m,n);//求得排列数,安排返回数组的第一维
int[,]arrange=newint[m,A];//定义返回数组
ArrayListe=newArrayList();//设置元素表
for(inti=0;i<n;i++)
e.Add(i+1);
Arrange(refarrange,e,m,0,0);
returnarrange;
}

///<summary>
///组合数函数
///</summary>
publicstaticintCombinationCount(intm,intn)
{
inta=Product(n-m+1,n),b=Product(2,m);//a=n-m+1*...*n;b=m!
return(int)a/b;//c=a/b
}

///<summary>
///生成组合表函数
///</summary>
publicstaticint[,]Combination(intm,intn)
{
intA=CombinationCount(m,n);//求得排列数,安排返回数组的第一维
int[,]combination=newint[m,A];//定义返回数组
ArrayListe=newArrayList();//设置元素表
for(inti=0;i<n;i++)
e.Add(i+1);
Combination(refcombination,e,m,0,0);
returncombination;
}


#endregion

#region内部核心

///<summary>
///排列函数
///</summary>
///<paramname="reslut">返回值数组</param>
///<paramname="elements">可供选择的元素数组</param>
///<paramname="m">目标选定元素个数</param>
///<paramname="x">当前返回值数组的列坐标</param>
///<paramname="y">当前返回值数组的行坐标</param>
privatestaticvoidArrange(refint[,]reslut,ArrayListelements,intm,intx,inty)
{
intsub=ArrangeCount(m-1,elements.Count-1);//求取当前子排列的个数
for(inti=0;i<elements.Count;i++,y+=sub)//每个元素均循环一次,每次循环后移动行指针
{
intval=RemoveAndWrite(elements,i,refreslut,x,y,sub);
if(m>1)//递归条件为子排列数大于1
Arrange(refreslut,elements,m-1,x+1,y);
elements.Insert(i,val);//恢复刚才删除的元素
}
}

///<summary>
///组合函数
///</summary>
///<paramname="reslut">返回值数组</param>
///<paramname="elements">可供选择的元素数组</param>
///<paramname="m">目标选定元素个数</param>
///<paramname="x">当前返回值数组的列坐标</param>
///<paramname="y">当前返回值数组的行坐标</param>
privatestaticvoidCombination(refint[,]reslut,ArrayListelements,intm,intx,inty)
{
ArrayListtmpElements=newArrayList();//所有本循环使用的元素都将暂时存放在这个数组
intelementsCount=elements.Count;//先记录可选元素个数
intsub;
for(inti=elementsCount-1;i>=m-1;i--,y+=sub)//从elementsCount-1(即n-1)到m-1的循环,每次循环后移动行指针
{
sub=CombinationCount(m-1,i);//求取当前子组合的个数
intval=RemoveAndWrite(elements,0,refreslut,x,y,sub);
tmpElements.Add(val);//把这个可选元素存放到临时数组,循环结束后一并恢复到elements数组中
if(sub>1||(elements.Count+1==m&&elements.Count>0))//递归条件为子组合数大于1或可选元素个数+1等于当前目标选择元素个数且可选元素个数大于1
Combination(refreslut,elements,m-1,x+1,y);
}
elements.InsertRange(0,tmpElements);//一次性把上述循环删除的可选元素恢复到可选元素数组中
}

///<summary>
///返回由Index指定的可选元素值,并在数组中删除之,再从y行开始在x列中连续写入subComb个值
///</summary>
privatestaticintRemoveAndWrite(ArrayListelements,intindex,refint[,]reslut,intx,inty,intcount)
{
intval=(int)elements[index];
elements.RemoveAt(index);
for(inti=0;i<count;i++)
reslut[x,y+i]=val;
returnval;
}

#endregion
}




测试窗体frmTest.cs代码清单:

usingSystem;
usingSystem.Drawing;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Windows.Forms;
usingSystem.Data;

namespaceCombinatoricsLib
{
///<summary>
///Form1的摘要说明。
///</summary>
publicclassfrmTest:System.Windows.Forms.Form
{
privateSystem.Windows.Forms.DataGridgridShow;
privateSystem.Windows.Forms.NumericUpDownnumM;
privateSystem.Windows.Forms.ButtonbtnGo;
privateSystem.Windows.Forms.DomainUpDowndomainFunction;
privateSystem.Windows.Forms.StatusBarstatusBar1;
privateSystem.Windows.Forms.StatusBarPanelpanelErrMsg;
privateSystem.Windows.Forms.NumericUpDownnumN;
///<summary>
///必需的设计器变量。
///</summary>
privateSystem.ComponentModel.Containercomponents=null;

publicfrmTest()
{
//
//Windows窗体设计器支持所必需的
//
InitializeComponent();

//
//TODO:在InitializeComponent调用后添加任何构造函数代码
//
}

///<summary>
///清理所有正在使用的资源。
///</summary>
protectedoverridevoidDispose(booldisposing)
{
if(disposing)
{
if(components!=null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}

#regionWindows窗体设计器生成的代码
///<summary>
///设计器支持所需的方法-不要使用代码编辑器修改
///此方法的内容。
///</summary>
privatevoidInitializeComponent()
{
this.gridShow=newSystem.Windows.Forms.DataGrid();
this.domainFunction=newSystem.Windows.Forms.DomainUpDown();
this.numM=newSystem.Windows.Forms.NumericUpDown();
this.numN=newSystem.Windows.Forms.NumericUpDown();
this.btnGo=newSystem.Windows.Forms.Button();
this.statusBar1=newSystem.Windows.Forms.StatusBar();
this.panelErrMsg=newSystem.Windows.Forms.StatusBarPanel();
((System.ComponentModel.ISupportInitialize)(this.gridShow)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numM)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numN)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.panelErrMsg)).BeginInit();
this.SuspendLayout();
//
//gridShow
//
this.gridShow.AlternatingBackColor=System.Drawing.Color.Lavender;
this.gridShow.BackColor=System.Drawing.Color.WhiteSmoke;
this.gridShow.BackgroundColor=System.Drawing.Color.LightGray;
this.gridShow.BorderStyle=System.Windows.Forms.BorderStyle.None;
this.gridShow.CaptionBackColor=System.Drawing.Color.LightSteelBlue;
this.gridShow.CaptionForeColor=System.Drawing.Color.MidnightBlue;
this.gridShow.DataMember="";
this.gridShow.FlatMode=true;
this.gridShow.Font=newSystem.Drawing.Font("Tahoma",8F);
this.gridShow.ForeColor=System.Drawing.Color.MidnightBlue;
this.gridShow.GridLineColor=System.Drawing.Color.Gainsboro;
this.gridShow.GridLineStyle=System.Windows.Forms.DataGridLineStyle.None;
this.gridShow.HeaderBackColor=System.Drawing.Color.MidnightBlue;
this.gridShow.HeaderFont=newSystem.Drawing.Font("Tahoma",8F,System.Drawing.FontStyle.Bold);
this.gridShow.HeaderForeColor=System.Drawing.Color.WhiteSmoke;
this.gridShow.LinkColor=System.Drawing.Color.Teal;
this.gridShow.Location=newSystem.Drawing.Point(24,88);
this.gridShow.Name="gridShow";
this.gridShow.ParentRowsBackColor=System.Drawing.Color.Gainsboro;
this.gridShow.ParentRowsForeColor=System.Drawing.Color.MidnightBlue;
this.gridShow.ReadOnly=true;
this.gridShow.SelectionBackColor=System.Drawing.Color.CadetBlue;
this.gridShow.SelectionForeColor=System.Drawing.Color.WhiteSmoke;
this.gridShow.Size=newSystem.Drawing.Size(648,344);
this.gridShow.TabIndex=0;
//
//domainFunction
//
this.domainFunction.BackColor=System.Drawing.SystemColors.Info;
this.domainFunction.Font=newSystem.Drawing.Font("宋体",36F,System.Drawing.FontStyle.Regular,System.Drawing.GraphicsUnit.Point,((System.Byte)(134)));
this.domainFunction.ForeColor=System.Drawing.Color.Teal;
this.domainFunction.Items.Add("C");
this.domainFunction.Items.Add("A");
this.domainFunction.Location=newSystem.Drawing.Point(24,8);
this.domainFunction.Name="domainFunction";
this.domainFunction.ReadOnly=true;
this.domainFunction.Size=newSystem.Drawing.Size(48,62);
this.domainFunction.TabIndex=1;
this.domainFunction.Text="C";
//
//numM
//
this.numM.BackColor=System.Drawing.Color.PeachPuff;
this.numM.Font=newSystem.Drawing.Font("宋体",12F,System.Drawing.FontStyle.Regular,System.Drawing.GraphicsUnit.Point,((System.Byte)(134)));
this.numM.ForeColor=System.Drawing.Color.Teal;
this.numM.Location=newSystem.Drawing.Point(80,8);
this.numM.Maximum=newSystem.Decimal(newint[]{
20,
0,
0,
0});
this.numM.Minimum=newSystem.Decimal(newint[]{
1,
0,
0,
0});
this.numM.Name="numM";
this.numM.Size=newSystem.Drawing.Size(56,26);
this.numM.TabIndex=4;
this.numM.Value=newSystem.Decimal(newint[]{
2,
0,
0,
0});
//
//numN
//
this.numN.BackColor=System.Drawing.Color.Bisque;
this.numN.Font=newSystem.Drawing.Font("宋体",12F);
this.numN.ForeColor=System.Drawing.Color.Teal;
this.numN.Location=newSystem.Drawing.Point(80,40);
this.numN.Maximum=newSystem.Decimal(newint[]{
25,
0,
0,
0});
this.numN.Minimum=newSystem.Decimal(newint[]{
1,
0,
0,
0});
this.numN.Name="numN";
this.numN.Size=newSystem.Drawing.Size(56,26);
this.numN.TabIndex=5;
this.numN.Value=newSystem.Decimal(newint[]{
4,
0,
0,
0});
//
//btnGo
//
this.btnGo.BackColor=System.Drawing.Color.PaleTurquoise;
this.btnGo.Location=newSystem.Drawing.Point(184,24);
this.btnGo.Name="btnGo";
this.btnGo.Size=newSystem.Drawing.Size(88,32);
this.btnGo.TabIndex=6;
this.btnGo.Text="Go!";
this.btnGo.Click+=newSystem.EventHandler(this.btnGo_Click);
//
//statusBar1
//
this.statusBar1.Location=newSystem.Drawing.Point(0,453);
this.statusBar1.Name="statusBar1";
this.statusBar1.Panels.AddRange(newSystem.Windows.Forms.StatusBarPanel[]{
this.panelErrMsg});
this.statusBar1.ShowPanels=true;
this.statusBar1.Size=newSystem.Drawing.Size(704,32);
this.statusBar1.TabIndex=7;
this.statusBar1.Text="statusBar1";
//
//panelErrMsg
//
this.panelErrMsg.AutoSize=System.Windows.Forms.StatusBarPanelAutoSize.Contents;
this.panelErrMsg.Text="Idle";
this.panelErrMsg.Width=39;
//
//frmTest
//
this.AutoScaleBaseSize=newSystem.Drawing.Size(6,14);
this.ClientSize=newSystem.Drawing.Size(704,485);
this.Controls.Add(this.statusBar1);
this.Controls.Add(this.btnGo);
this.Controls.Add(this.numN);
this.Controls.Add(this.numM);
this.Controls.Add(this.domainFunction);
this.Controls.Add(this.gridShow);
this.MaximizeBox=false;
this.Name="frmTest";
this.StartPosition=System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text="frmTest";
((System.ComponentModel.ISupportInitialize)(this.gridShow)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numM)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numN)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.panelErrMsg)).EndInit();
this.ResumeLayout(false);

}
#endregion

///<summary>
///应用程序的主入口点。
///</summary>
[STAThread]
staticvoidMain()
{
Application.Run(newfrmTest());
}

privatevoidbtnGo_Click(objectsender,System.EventArgse)
{
int[,]reslut;
intm=(int)numM.Value,n=(int)numN.Value;

if(m<=n)
{
panelErrMsg.Text="Running...";
if(domainFunction.Text=="A")
reslut=Combinatorics.Arrange(m,n);
else
reslut=Combinatorics.Combination(m,n);
panelErrMsg.Text="Showing...";
gridShow.DataSource=Combinatorics.TwoDemisionIntArrayToDataTable(reslut);
panelErrMsg.Text="Idle";
}
else
panelErrMsg.Text="Inputnumberisinvalid";
}
}
}

你可能感兴趣的:(C++,c,算法,windows,C#)