不重复的随机数 [英] Non-repetitive random number

查看:175
本文介绍了不重复的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要从1-20生成随机数我需要挑选选择性,它不应该是重复的。

To generate Random numbers from 1- 20 I need to pick selective and it should not be repetitive.

如何做到这一点在C#

请注意我需要遍历像这样

Note I need to loop through as like this

Random rnd = new Random()
rnd.Next(1,20)
for(int i =0; i<=20;i++)
{

}

有关所有的循环数目应为1至20个

For all the loops number should be 1 to 20

推荐答案

究竟你不应该重复是什么意思?如果你的意思是你不想要得到的任何的重复,那么你应该基本上都坐号1-20的名单,他们洗牌,然后从的头抢一次名单。对于一个有效的方式来洗牌列表,请参阅this堆栈溢出的答案

What exactly do you mean by "should not be repetitive"? If you mean that you don't want to get any duplicates, then you should basically take a list of the numbers 1-20, shuffle them, and then grab one at a time from the head of the list. For an efficient way to shuffle a list, see this Stack Overflow answer.

如果你只是意味着你当前的尝试给5,5,5,5,5,5,1,1,1,1,1,1,1,1,2,2,2,2,2等那么很可能你正在创建随机每次挑一些时间的新实例:不这样做。每次创建一个实例的时候,它会使用当前时间作为种子的随机数发生器(除非你指定一个明确的)。这意味着如果你创建快速连续的几个实例,每个将获得相同的种子,因此给予相同的数字序列。

If you just mean that your current attempt gives 5, 5, 5, 5, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 etc then chances are you're creating a new instance of Random each time you pick a number: don't do that. Each time you create an instance, it will use the current time as the "seed" for the random number generator (unless you specify one explicitly). That means if you create several instances in quick succession, each will get the same seed and therefore give the same sequence of numbers.

相反,使用随机的一个实例,并重新使用它。 (请注意,这不是线程安全的,虽然,这是一种痛苦。)例如:

Instead, use a single instance of Random and reuse it. (Note that it's not thread-safe though, which is a pain.) For instance:

private static readonly Random Rng = new Random();

public int NextNumber()
{
    return Rng.Next(20) + 1;
}

这不会是线程安全的,但我们知道这是一个问题。另一种方法是,有时要通过随机进入方法(这通常会比较复杂,当然):

That won't be thread-safe, but let us know if that's a problem. An alternative is sometimes to pass the Random into the method (which would normally be more complicated, of course):

public int NextNumber(Random rng)
{
    return rng.Next(20) + 1;
}

然后调用者可以适当地重用实例。

then the caller can reuse the instance appropriately.

如果你想生成随机数的线程安全的方式,你可能想看看我的<一个href=\"http://www.yoda.arachsys.com/csharp/miscutil/usage/staticrandom.html\"><$c$c>StaticRandom MiscUtil

If you want a thread-safe way of generating random numbers, you might want to look at my StaticRandom class in MiscUtil.

(请注意,使用 rng.Next(1,21)也工作得很好 - 我碰巧preFER以上的版本,因为我觉得它减少了猜测关于包容/独家边界,但它是个人喜好问题。)

(Note that using rng.Next(1, 21) would also work fine - I happen to prefer the version above as I think it reduces the guesswork about inclusive/exclusive boundaries, but it's a matter of personal taste.)

这篇关于不重复的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆