[英]Nested random generator is not random
I have the following code. 我有以下代码。 Random r works and gets me about 10% into the if.
随机r可以使if大约占10%。 However rr doesn't seem to work.
但是rr似乎不起作用。 It always returns 0. What am I doing wrong?
它总是返回0。我在做什么错?
I want to choose between two choices randomly only 10% of the time. 我只想在10%的时间内随机选择两个选项。 This is in an asp.net app.
这是在asp.net应用程序中。 The code gets executed on button click.
单击按钮即可执行代码。
Random r = new Random();
Random rr = new Random();
int randomnum = r.Next(0, 100);
if (randomnum <= 10)
{
int randompick = rr.Next(0, 2);
if (randompick == 0)
{
If you are happy with the outer loop's randomness, consider 如果您对外部循环的随机性感到满意,请考虑
int randompick = randomnum % 2;
instead of the nested Random object. 而不是嵌套的Random对象。
您可以将相同的Random
对象用于两个随机选择,对吗?
As noted, you should use just one pseudorandom stream and instantiate it just once. 如前所述,您应该只使用一个伪随机流并将其实例化一次。 I'd struct my solution along these lines:
我将按照以下思路构建解决方案:
class SomeWidget
{
private static Random rng ;
static SomeWidget()
{
rng = new Random() ;
return ;
}
public SomeWidget()
{
return ;
}
public int DoOneThing90PercentOfTheTimeAndSomethingElseTheRestOfTheTime()
{
int rc ;
int n = rng.Next() % 10 ; // get a number in the range 0 - 9 inclusive.
if ( n != 0 ) // compare to whatever value you wish: 0, 1, 2, 3, 4, 5, 6, 8 or 9. It makes no nevermind
{
rc = TheNinetyPercentSolution() ;
}
else
{
rc = TheTenPercentSolution() ;
}
return rc ;
}
private int TheTenPercentSolution()
{
int rc ;
int n = rng.Next() % 2 ;
if ( n == 0 )
{
rc = DoOneThing() ;
}
else
{
rc = DoAnotherThing() ;
}
return rc ;
}
private int DoOneThing()
{
return 1;
}
private int DoAnotherThing()
{
return 2 ;
}
private int TheNinetyPercentSolution()
{
return 3 ;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.