开发者

How do I have two randoms in a row give different values?

For example, if I have a class:

public class Class
{
public Random r;

public Class()
{r= new Random()}
}

and later create two instances of it:

Class a = new Class();
Class b = new Class();

and call r sequentially, the r for both will give the same values. I've read that this is because the defa开发者_C百科ult constructor for Random uses the time to provide "randomness," so I was wondering how I could prevent this. Thanks in advance!


One way to achieve that would be to make r static.

static means that only one Random r will exist, and it will be shared across all instances of the class.

You code would look like this:

public class Class() { static Random r = new Random(); }

Class a = new Class();
Class b = new Class();

If you're using threading, you can make it [ThreadStatic] (so that each thread uses its own instance of the Random class)

There's info on how to use [ThreadStatic] here - I haven't used it myself, but it looks quite cool and nifty, and gets rid of any potential threading-related woes.


Constructor of Random class is based on time. So when you creating them in quick sequence - they get the same seed and then will produce same values.

So you need to share Random for your classes with some way -or- provide a different initial seed yourself.


One possibility in this case is to make the Random a static so that it is only instantiated once.

public class Class{
  private static Random r = new Random();        
  //the rest of your class
}

The problem is that you create the two classes at almost the same time, therefore they will use the same seed (since it's based of the current time among other things), and will produce the same sequence of numbers.


Try this:

public class TestClass
{
    private static int seed = Environment.TickCount;


    public TestClass()
    {
        DoStuff();
        DoStuff();
        DoStuff();
        DoStuff();
    }

    private void DoStuff()
    {
        var random = new Random(seed++);
        int index = random.Next(30) + 1;

        //Console.Write(index);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜