dimanche 11 septembre 2016

C#'s Random producing recognisable pattern when using sequential seeds

Given the following:

for(int seed = 0; seed < 100; seed++) {
    var random = new Random(seed);
    var roll = (random.Next() % 6) + 1;
    Console.Write(roll + " ");
}

I'm seeing a clear pattern in the output:

1 1 2 2 3 3 4 4 5 5 6 6 1 1 1 2 2 3 3 4 4 5 5 6 6
1 1 2 2 3 3 4 4 5 5 5 6 6 1 1 2 2 3 3 4 4 5 5 6 6
1 1 2 2 3 3 4 4 4 5 5 6 6 1 1 2 2 3 3 4 4 5 5 6 6
1 1 2 2 3 3 3 4 4 5 5 6 6 1 1 2 2 3 3 4 4 5 5 6 6

I do understand that recreating a new Random object every time with a sequential seed isn't the "proper" way of using the class, and that strictly speaking I should be keep the Random instance around, calling Next() on it each time.

However, my use case is that I need to be able to exit my program and restore the state at any moment, and continue the sequence of number.

I also need the user to be able to set a seed manually, so I was hoping to be able to do something like:

var random = new Random(userSeed + nextValueIndex);
var chosenValue = random.Next();

I've also tried random.Next(min, max), and it gives different results, but also in a clear pattern.

Clearly my approach isn't the right way to use the Random class, but what is, for my use case?

I understand that random number generation is a very complex topic, so while I'm sort of interested in an explanation of why this is happening, I'm most interested in a practical (easy?) solution ;-)




Aucun commentaire:

Enregistrer un commentaire