在字符串中生成4个唯一编号

时间:2015-05-14 16:25:35

标签: c#

我想生成一个4位数的字符串,这些数字不能被替换并再次使用,例如:1234是可以接受的,1223不是!

P.S:我老师问我的时候我不能用!没有数组或循环!

Random Item = new Random(); 
int Num1, Num2, Num3, Num4; 
do { 
    Num1 = Item.Next(0, 10); 
    Num2 = Item.Next(0, 10); 
    Num3 = Item.Next(0, 10); 
    Num4 = Item.Next(0, 10); 
} while (Num1 == Num2 || Num1 == Num3 
            || Num1 == Num4 || Num2 == Num3 
            || Num2 == Num4 || Num3 == Num4);

string Source = string.Format("{0}{1}{2}{3}", Num1, Num2, Num3, Num4);

3 个答案:

答案 0 :(得分:0)

使用LINQ:

height

答案 1 :(得分:0)

试试这个

width

答案 2 :(得分:0)

以下是您的解决方案:

namespace ClassLibrary1
{
    public class Class1
    {
        public void Generate()
        {
            string remainingDigits = "0123456789";
            System.Random r = new System.Random();
            string output = null;
            int count = 10;
            int index = r.Next(count);
            output += remainingDigits[index];
            remainingDigits = remainingDigits.Remove(index, 1);
            count -= 1;
            index = r.Next(count);
            output += remainingDigits[index];
            remainingDigits = remainingDigits.Remove(index, 1);
            count -= 1;
            index = r.Next(count);
            output += remainingDigits[index];
            remainingDigits = remainingDigits.Remove(index, 1);
            count -= 1;
            index = r.Next(count);
            output += remainingDigits[index];
        }
    }
}