生成不重复随机数的疑问(C#)?
C# code
protected void Button1_Click(object sender, EventArgs e)
{
s="17,18,19,20";
//输出随机生成的红号和蓝号列表
string[] ss = s.Split(',');
for (int x = 0; x < ss.Length; x++)
{
Response.Write("红号" + getRedCode() + "蓝号" + ss[x].ToString()+"<br>");
}
}
public string getRedCode()
{
string str = "";
Hashtable hashtable = new Hashtable();
Random rm = new Random();
int RmNum = 6;
for (int i = 0; hashtable.Count < RmNum; i++)
{
int nValue = rm.Next(34);
if (!hashtable.ContainsValue(nValue) && nValue != 0)
{
hashtable.Add(nValue, nValue);
str+=nValue.ToString()+",";
}
}
return str.Remove(str.Length - 1);
}
如上代码,为什么每次生成的红号都是重复的?
怎么才能不重复?
------解决方案--------------------随机种子呢?
一般用系统时间来作为随机种子
------解决方案--------------------一定要结贴,给分!
你的问题就在于每次都用的是同一个Random实例,所以结果会是一样。
protected void Page_Load(object sender, EventArgs e)
{
CaptionLabel.Text = "<h3>输出随机生成的红号和蓝号列表</h3>";
string s = "17,18,19,20";
InforLabel01.Text = "";
InforLabel01.Text += s + "<br/>";
//输出随机生成的红号和蓝号列表
string[] ss = s.Split(',');
for (int x = 0; x < ss.Length; x++)
{
InforLabel01.Text += "<span style='color:red;'>红号" + getRedCode() + "</span><span style='color:blue;'>蓝号" + ss[x].ToString() + "</span><br>";
}
}
public string getRedCode()
{
string str = "";
Hashtable vHashtable = new Hashtable();
int RmNum = 10;
for (int i = 0; vHashtable.Count < RmNum; i++)
{
Random vRandom = new Random();
int nValue = vRandom.Next(1, 1000);
if (vHashtable.ContainsValue(nValue) == false)
{
vHashtable.Add(nValue, nValue);
str += nValue.ToString() + ",";
}
}
return str.Substring(0, str.Length - 1);
}