預設情況下,.NET的隨機數是根據系統時間來產生的,如果電腦速度很快的話,產生的隨機數就會一樣。
Random rnd = new Random();
int rndNum = rnd.Next(); //int 取值範圍內的隨機數
int rndNum = rnd.Next(10); //得0~9的隨機數
int rndNum = rnd.Next(10,20); //得10~19的隨機數
int rndNum = rnd.NextDouble(); //得0~1的隨機數
若隨機種子為系統時間,用迴圈一次產生多個隨機數.
因為CPU運算速度太快了,所以每次取到的都是同一個時間.即產生的數字都一樣了.
所以要不停地變換種子. public string GetRandomCode()
{
char[] chars = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'
};
string code = string.Empty;
for (int i = 0; i < 4; i++)
{
//這裡是關鍵,傳入一個seed參數即可保證產生的隨機數不同
//Random rnd = new Random(unchecked((int)DateTime.Now.Ticks));
Random rnd = new
Random(GetRandomSeed( ));
code += chars[rnd.Next(0, 30)].ToString();
}
return code;
}
/// <summary>
/// 加密隨機數產生器 產生隨機種子
/// </summary>
/// <returns></returns>
staticint GetRandomSeed()
{
byte[] bytes =
newbyte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
returnBitConverter.ToInt32(bytes, 0);
}
擷取指定數量的隨機組合 洗牌程式 思路
public static IList<string> CreateChargeCodeNo(string PromotionChargeCodeNo, int Count)
{
List<string> lis = new List<string>();
if (string.IsNullOrEmpty(PromotionChargeCodeNo))
{
return lis;
}
string ChargeCodeNo = PromotionChargeCodeNo;
int length = 10 - PromotionChargeCodeNo.Length;
while (lis.Count < Count)
{
int[] numbers = new int[length * 2];
for (int i = 0; i < length * 2; i++)
numbers[i] = i + 1;
for (int i = 0; i < length * 2; i++)//二倍體洗牌
{
Random rand = new Random(GetRandomSeed());
int temp = rand.Next(length * 2);
int tempNumber = numbers[i];
numbers[i] = numbers[temp];
numbers[temp] = tempNumber;
}
string code = "";
for (int x = 0; code.Length < length; x++)
{
code += numbers[x];
}
code = code.Substring(0, length);
string s = ChargeCodeNo + code;
if (lis.Contains(s))
{
continue;
}
lis.Add(ChargeCodeNo + code);
}
return lis;
}