生成随机的唯一值 C# [英] Generating random, unique values C#
问题描述
我已经搜索了一段时间并且一直在努力找到这个,我正在尝试生成几个随机的、唯一的数字是 C#.我正在使用 System.Random
,我正在使用 DateTime.Now.Ticks
种子:
I've searched for a while and been struggling to find this, I'm trying to generate several random, unique numbers is C#. I'm using System.Random
, and I'm using a DateTime.Now.Ticks
seed:
public Random a = new Random(DateTime.Now.Ticks.GetHashCode());
private void NewNumber()
{
MyNumber = a.Next(0, 10);
}
我定期调用 NewNumber()
,但问题是我经常收到重复的数字.有人建议,因为我每次都声明随机数,它不会产生随机数,所以我把声明放在我的函数之外.有什么建议或比使用 System.Random
更好的方法?谢谢
I'm calling NewNumber()
regularly, but the problem is I often get repeated numbers. Some people suggested because I was declaring the random every time I did it, it would not produce a random number, so I put the declaration outside my function. Any suggestions or better ways than using System.Random
? Thank you
推荐答案
我经常调用 NewNumber(),但问题是我经常遇到重复的数字.
I'm calling NewNumber() regularly, but the problem is I often get repeated numbers.
Random.Next
不保证数字是唯一的.此外,您的范围是从 0 到 10,您可能会得到重复的值.也许您可以设置一个 int
列表,并在检查它是否不包含重复项后在列表中插入随机数.类似的东西:
Random.Next
doesn't guarantee the number to be unique. Also your range is from 0 to 10 and chances are you will get duplicate values. May be you can setup a list of int
and insert random numbers in the list after checking if it doesn't contain the duplicate. Something like:
public Random a = new Random(); // replace from new Random(DateTime.Now.Ticks.GetHashCode());
// Since similar code is done in default constructor internally
public List<int> randomList = new List<int>();
int MyNumber = 0;
private void NewNumber()
{
MyNumber = a.Next(0, 10);
if (!randomList.Contains(MyNumber))
randomList.Add(MyNumber);
}
这篇关于生成随机的唯一值 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!