当前位置:编程学习 > C#/ASP.NET >>

用1234四个数组成不同的三位数 要求个位 十位 百位上的数字都不相同

请高人指点 谢谢了 --------------------编程问答--------------------
string base_string = "1234";
string result = base_string.Remove(new Random(Environment.TickCount).Next(0, base_string.Length - 1),1);
--------------------编程问答--------------------
List<int> ret=new List<int>();//保存结果
int[] arr = new int[] { 1, 2, 3, 4 };
int[] temp = new int[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
    temp[0]=arr[i];
    for(int j=0;j<arr.Length;j++)
    {
        temp[1]=arr[j];
        for(int p=0;p<arr.Length;p++)
        {
            if(temp[1]==arr[p]) continue;
            temp[2]=arr[p];
            for(int q=0;q<arr.Length;q++)
            {
                if (temp[2] == arr[q] || temp[1] == arr[q]) continue;
                temp[3]=arr[q];
                ret.Add(temp[0]*1000+temp[1]*100+temp[2]*10+temp[3]);
            }
        }
    }

}


当然可用递归 --------------------编程问答-------------------- 全排列组合
http://topic.csdn.net/u/20090217/21/f41ed9f6-f929-451c-a5c9-80d2e408422a.html --------------------编程问答-------------------- C语言版,比较简单的方法,自己翻译成c#吧

1.程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去掉不满足条件的排列。 
2.程序源代码:

main()
{
int i,j,k;
printf("\n");
for(i=1;i<5;i++)    /*以下为三重循环*/
 for(j=1;j<5;j++) 
  for (k=1;k<5;k++)
   {
    if (i!=k&&i!=j&&j!=k)    /*确保i、j、k三位互不相同*/
    printf("%d,%d,%d\n",i,j,k);
   }
}

--------------------编程问答--------------------

/// <summary>
/// 从n个数中选出各不相同的m个数
/// </summary>
public class Cnm
{
private List<int> lstSrc;//源数据集合
int[] current; //当前组合
bool alreadyEnd; //组合已经到达末尾
 
public Cnm(int[] src,int m)
{
if (m > src.Length)
{
throw new ArgumentException("参数m不能大于数组长度");
}
this.lstSrc = new List<int>(src);
lstSrc.Sort();
if (lstSrc.Count > 0)
{
current = new int[m];
Array.Copy(lstSrc.ToArray(), 0, current, 0, m);
}
else
{
alreadyEnd = true;
}
}

    //由当前组合获取下一个组合
void Next()
{
int index=0;
int i = current.Length - 1;
for (; i>-1; i--)
{
index = lstSrc.LastIndexOf(current[i]);
if (index< lstSrc.Count +i-current.Length)
{
for (int j = i; j< current.Length; j++)
{
current[j] = lstSrc[index + 1+j-i];
}
break;
}
            }

alreadyEnd = (i == -1);
}

public IEnumerator GetEnumerator()
{
while (!alreadyEnd)
{
yield return current;
Next();
if (alreadyEnd)
{
break;
}
}
}
}

           private void button2_Click(object sender, EventArgs e)
{

    int[] src = new int[] { 1, 2, 3, 4, 5 };
    Cnm c = new Cnm(src, 3);
    IEnumerator ienumer= c.GetEnumerator();
int []item=null;
long count = 0;
while (ienumer.MoveNext())
{
item = ienumer.Current as int[];
for (int i = 0; i < item.Length; i++)
{
Console.Write(item[i] + " ");
}
Console.WriteLine();
count++;
}
Console.WriteLine("组合总数:"+count);
                }
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,