在C#中的非重复的随机数 [英] Non duplicate random numbers in C#
问题描述
我想创建一个范围1之间的非重复的随机数 - 10,我计划通过存储我做在一个阵列中的每个随机数,这样做的,然后每天以确保我没有时间检查数组已使用的数量。
我的问题是,而不是创建不同的随机数,如1,2,3我只是不停地一遍又一遍地得到相同的随机数。
randomNumber();
Label1.Text = randomRow +;
randomNumber();
Label2.Text = randomRow +;
randomNumber();
Label3.Text = randomRow +; 公众诠释randomNumber()
{
清单< INT>数=新的List< INT>();
INT NUM = 0;
随机randNum =新的随机();
NUM = randNum.Next(1,11); 如果(numbers.Contains(NUM))
{
NUM = randNum.Next(1,11);
}
其他
{
randomRow = NUM;
numbers.Add(NUM);
} 返回randomRow;
}
问题:每次你正在创建太近时间 RandomNumber
对象。
当你创建一个随机的对象,它的种子来自系统时钟的值。如果创建随机实例太近的时候,他们都将使用相同的随机序列种子。
从<一个href=\"http://stackoverflow.com/questions/1654887/random-next-returns-always-the-same-values\">Here
当你创建一个随机的对象,它的种子从一个值
系统时钟。如果创建随机实例太近的时候,他们
将全部具有相同的随机序列被接种
块引用>解决方案:
移动
随机randNum =新的随机();
之外的功能randomNumber()
试试这个:
随机randNum =新的随机();
公众诠释randomNumber()
{
清单&LT; INT&GT;数=新的List&LT; INT&GT;();
INT NUM = 0; NUM = randNum.Next(1,11); 如果(numbers.Contains(NUM))
{
NUM = randNum.Next(1,11);
}
其他
{
randomRow = NUM;
numbers.Add(NUM);
} 返回randomRow;
}I am trying to create a range of non duplicate random numbers between 1 - 10, I planned on doing this by storing each random number I made in to an array and then checking that array every time to make sure I ain't already used the number.
My problem is that instead of creating different random numbers such as 1, 2, 3 I just keep getting the same random number over and over.
randomNumber(); Label1.Text = randomRow + ""; randomNumber(); Label2.Text = randomRow + ""; randomNumber(); Label3.Text = randomRow + ""; public int randomNumber() { List<int> numbers = new List<int>(); int num = 0; Random randNum = new Random(); num = randNum.Next(1, 11); if (numbers.Contains(num)) { num = randNum.Next(1, 11); } else { randomRow = num; numbers.Add(num); } return randomRow; }
解决方案Problem : everytime you are creating the
RandomNumber
object in too close time.When you create a Random object, it's seeded with a value from the system clock. If you create Random instances too close in time, they will all be seeded with the same random sequence.
From Here
When you create a Random object, it's seeded with a value from the system clock. If you create Random instances too close in time, they will all be seeded with the same random sequence.
Solution :
move
Random randNum = new Random();
outside the functionrandomNumber()
.Try This:
Random randNum = new Random(); public int randomNumber() { List<int> numbers = new List<int>(); int num = 0; num = randNum.Next(1, 11); if (numbers.Contains(num)) { num = randNum.Next(1, 11); } else { randomRow = num; numbers.Add(num); } return randomRow; }
这篇关于在C#中的非重复的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!