user794479
user794479

Reputation: 417

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 default constructor for Random uses the time to provide "randomness," so I was wondering how I could prevent this. Thanks in advance!

Upvotes: 5

Views: 175

Answers (4)

William Lawn Stewart
William Lawn Stewart

Reputation: 1205

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.

Upvotes: 5

Ivan Danilov
Ivan Danilov

Reputation: 14787

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.

Upvotes: 4

Rumplin
Rumplin

Reputation: 2768

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);
    }
}

Upvotes: 1

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60744

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.

Upvotes: 2

Related Questions