views:

74

answers:

2

I need a seed for an instance of C#'s Random class, and I read that most people use the current time's ticks counter for this. But that is a 64-bit value and the seed needs to be a 32-bit value. Now I thought that the GetHashCode() method, which returns an int, should provide a reasonably distributed value for its object and this may be used to avoid using only the lower 32-bits of the tick count. However, I couldn't find anything about the GetHashCode() of the Int64 datatype.

So, I know that it will not matter much, but will the following work as good as I think (I can't trial-and-error randomness), or maybe it works the same as using (int)DateTime.Now.Ticks as the seed? Or maybe it even works worse? Who can shed some light on this.

int seed = unchecked(DateTime.Now.Ticks.GetHashCode());
Random r = new Random(seed);

Edit: Why I need a seed and don't just let the Random() constructor do the work? I need to send the seed to other clients which use the same seed for the same random sequence.

+7  A: 

new Random() already uses the current time. It is equivalent to new Random(Environment.TickCount).

But this is an implementation detail and might change in future versions of .net

I'd recommend using new Random() and only provide a fixed seed if you want to get a reproducible sequence of pseudo random values.

Since you need a known seed just use Environment.TickCount just like MS does. And then transmit it to the other program instances as seed.

CodeInChaos
+1 for mentioning that the only time to really provide your own seed value is when you want to reproduce a specific sequence of values. Think along the lines of the Windows Solitaire "game number" option.
Andrew Barber
I edited my question. I know about the `new Random()` constructor, but I need the seed.
Virtlink
A: 

If you need to seed it with something other than the current time (in which case you can use the default constructor), you can use this:

Random random = new Random(Guid.NewGuid().GetHashCode());
steinar
And why would that be a better value than `DateTime.Now.Ticks.GetHashCode()`?
Virtlink