Yesterday I wrote my first answer at Programming Puzzles & Code Golf. The question said this:
Given an input string
S
, printS
followed by a non-empty separator in the following way:
Step 1:
S
has a1/2
chance of being printed, and a1/2
chance for the program to terminate.Step 2:
S
has a2/3
chance of being printed, and a1/3
chance for the program to terminate.Step 3:
S
has a3/4
chance of being printed, and a1/4
chance for the program to terminate.…
Step
n
:S
has an/(n+1)
chance of being printed, and a1/(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()
returns0
), or - The program never stops (the calls to
Next()
never return0
).
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?
Note: I know that creating a single Random
object is the best practice, I just wanted to know a bit more than what the MSDN says:
The default seed value is derived from the system clock and has finite resolution.
What is that "finite resolution" the Random
class default constructor uses as seed? How much time should we separate the construction of two Random
objects to get different sequences? How much would those two different sequences differ when creating the Random
instances too close in time?