Random rand = new Random();
private string CreateRandomCode(int codeCount) //codeCount是希望生成的长度
{
string allChar = "A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,2,3,4,5,6,7,8,9" ;
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;

for(int i = 0; i < codeCount; i++)
{
if(temp != -1)
{
rand = new Random(i*temp*((int)DateTime.Now.Ticks));
}

int t = rand.Next(31);
if(temp == t)
{
return CreateRandomCode(codeCount);
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}这是随机生成密码的程序
怎样保证随机生成的密码没有重复的项啊?
谢谢

解决方案 »

  1.   

    什么叫没有重复的项?是指要生成6个字符的,abdeaf不允许么(其中a重复了)?
      

  2.   

    不是,是整个密码不能一样的
    rand = new Random(i*temp*((int)DateTime.Now.Ticks));
    这条语句应该有时间戳的功能啊,怎么生成的密码里面有很多的完全一样 的啊?
      

  3.   

    哪就用guid 了.这个生成的东西是不一样的.不过好长
      

  4.   

    don't create new Random(), use a single Random object, since your computer is too fast, DateTime.Now.Ticks don't always change, for example, runfor (int i=0;i<100;i++)
     Console.WriteLine(DateTime.Now.Ticks);
      

  5.   

    你的密码重复可能是因为两次调用的时间间隔太短了,时间上区别不出来,要想真正不重复,还是加上 Guid 吧。
      

  6.   

    在msdn上找到这个:
    但是,如果应用程序在一个较快的计算机上运行,则该计算机的系统时钟可能没有时间在此构造函数的调用之间进行更改,Random 的不同实例的种子值可能相同。这种情况下,请应用一个算法来区分每个调用的种子值。例如,以下的 C# 表达式使用按位求补运算来生成两个不同的种子值,即使系统时间值相同也可以。Random rdm1 = newRandom(unchecked((int)DateTime.Now.Ticks)); Random rdm2 = newRandom(~unchecked((int)DateTime.Now.Ticks)); 但是我这样写也不行的啊?
      

  7.   

    using System;
    using System.Collections;class PasswordGenerator
    {
        Random rand = new Random(); static void Main()
    { Hashtable ht = new Hashtable(); PasswordGenerator pw = new PasswordGenerator();
    for (int i=0; i < 10000; i++)
    {
    string s = pw.CreateRandomCode2(6);
    Console.WriteLine(s);
    if (ht.Contains(s))
    {
    Console.WriteLine("****something is wrong:" + s);
    return;
    }
    else
    ht[s] = "1";
    }

        } //产生的Code string每个字符都是无重复的
    private string CreateRandomCode(int codeCount) 
    {     char[] allCharArray = {'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z','2','3','4','5','6','7','8','9'};

    int last = allCharArray.Length - 1; for(int i = 0; i < codeCount; i++)
    {
    int t = rand.Next(last + 1);
    char temp = allCharArray[last];
    allCharArray[last] = allCharArray[t];
    allCharArray[t] = temp; last--;
    }

    return new String(allCharArray, last+1,codeCount);
    }
    private string CreateRandomCode2(int codeCount) 
    {     char[] allCharArray = {'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z','2','3','4','5','6','7','8','9'};
    char[] rc = new char[codeCount];
    int j=0;
    for(int i = 0; i < codeCount; i++)
    {
    int t = rand.Next(allCharArray.Length);
    rc[j++] = allCharArray[t];
    }

    return new String(rc, 0,codeCount);
    }
    }