Search code examples
c#randomiterator

C# System.Random Next comes out sorted


I am trying to access random elements from an array, but the Random generator that I am using keeps on giving me numbers in order like so:

Ordered Random

The numbers will always come out sequenced, never completely random (ie. the next number is always greater until the max is reached, then starts from low numbers again). This can be incremental or decremental as well.

I am using a seeded Random object and Random.Next(-100, 100). This is not the same as the behaviour demonstrated on the MSDN Random.Next page

All I can think of is that the version of .Net packaged with Unity does not have the most recent Random? Any solutions to this confusion?

//Example
//Seed and ods set before the Awake method is called
public int seed;
public GameObject[] pathPartOds;

Random random;
GameObject[] path;

void Awake () 
{
    random = new Random (seed);
}

void CreatePath (int length) 
{
    path = new GameObject[length];

    for (int i = 0; i < length; i++)
        path[i] = pathPartOds[random.Next (0, pathPartOds.length)];
}

Have used multiple seeds and they all give the same result, and I have been creating seeds using a random int


Solution

  • You need to create an instance of Random exactly once and pass that as a parameter into your function that draws a random number.

    Else you'll ruin the generator's statistical properties due to it being seeded in a systematic (i.e. non-random) way. That explains the piecewise monotonicity of your output.