Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Random codes - Is most of it simply wrong?

I had a lot of issues with randomizing lists. I am talking about a list of 200 elements, where I want to shuffle the list. Don't get me wrong, I read a lot of examples, and on first glance there are pretty nice things, like this:

Randomize a List<T>

But in my experience, at least on a fast machine, this is basically worthless. The shuffling works so fast that there is NOT a MS delay between two calls to Random.NEXT() which results in not nearly random behaviour.

I am NOT talking about super secure stuff, just a basic game random. I know I can add a delay of 1 MS, but this means "wasting" 200 MS just to randomize a list.

Now I found this approach: http://www.codinghorror.com/blog/2007/12/shuffling.html

It looks nice, using GUIDs to sort. BUT aren't they created the same way? Lets step it up a notch, lets assume I want to create 1000 numbers, between 0 - 5. This code is basically useless:

        var resultA = new List<int>();
        for (int i = 0; i < 1000; i++)
        {
            resultA.Add(new Random().Next(5));
        }


        var resultB = new List<int>();
        for (int i = 0; i < 1000; i++)
        {
            resultB.Add(new Random().Next(5));
            Thread.Sleep(1);
        }

A does not work at all, at least not im my environment in Windows Phone 7. B is fine, but it takes a second, which is also stupid. Any comments or thoughts, it can't be that hard to create a random list of integers :-)

like image 566
Christian Ruppert Avatar asked Nov 27 '22 06:11

Christian Ruppert


1 Answers

Don't keep initializing a new instance of Random; make just one and continually reference it.

var random = new Random();
var resultA = new List<int>();
for (int i = 0; i < 1000; i++)
{
    resultA.Add(random.Next(5));
}

You are correct that repeatedly creating new instances of Random within the same "timestamp" will result in the same seed; but calling .Next on an instance of Random "advances" the seed so that the next number you retrieve is (most likely) different.

This is also covered in the documentation on Random:

... because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers.

...

This problem can be avoided by creating a single Random object rather than multiple ones.

like image 178
Mark Rushakoff Avatar answered Dec 18 '22 00:12

Mark Rushakoff