mardi 13 juin 2017

Strange behaviour of Random.Next() method - how much does new Random() depends on time?

Yesterday I wrote my first answer at Programming Puzzles & Code Golf. The question said this:

Given an input string S, print S followed by a non-empty separator in the following way:

  • Step 1: S has a 1/2 chance of being printed, and a 1/2 chance for the program to terminate.

  • Step 2: S has a 2/3 chance of being printed, and a 1/3 chance for the program to terminate.

  • Step 3: S has a 3/4 chance of being printed, and a 1/4 chance for the program to terminate.

  • Step n: S has a n/(n+1) chance of being printed, and a 1/(n+1) chance for the program to terminate.

So I went and wrote this code (ungolfed):

Action<string> g = s =>
{
    var r = new Random();
    for (var i = 2; r.Next(i++) > 0;)
        Console.Write(s + " ");
};

This code works fine, but then someone said that I could save a few bytes creating the r variable inline, like this:

Action<string> g = s =>
{
    for (var i = 2; new Random().Next(i++) > 0;)
        Console.Write(s + " ");
};

I tried but when I executed the code, it always went in one of two possibilities:

  • Either the program halted before printing anything (the first call to Next() returns 0), or
  • The program never stops (the calls to Next() never return 0).

When I reverted the code to my original proposal, the program stopped more randomly as expected by the OP.

I know that the new Random() constructor depends on time, but how much? If I add a Sleep() call, the code behaviour starts to seem really random (but not much, the strings returned are still longer than the ones returned by the initial code):

Action<string> g = s =>
{
    for (var i = 2; new Random().Next(i++) > 0; Thread.Sleep(1))
        Console.Write(s + " ");
};

If I increment the sleep time to 10 ms, now the code really behaves like the original one.

So why is this? How much does the Random class depends on time? How exactly does the Random class seeds the number generator when calling the empty constructor?




Aucun commentaire:

Enregistrer un commentaire