9

I have this code:

var rand = new Random(0);
for(int i = 0; i < 100; i++)
{
  Console.WriteLine(rand.Next(0, 100));
}

And program should give me 100 times the same number (because seed is the same), but it gives different numbers...
Why?

Edit:
When I will do

for(int i = 0; i < 100; i++)
{
  Console.WriteLine(new Random(0).Next);
}

That returns the same number every time. That means, seed is changing? If yes, how? Is it increasing?

TheChilliPL
  • 337
  • 1
  • 5
  • 14
  • 2
    Next progresses the random number generator to generate a new random. In your example, you seed once and call 100 Next(); – Shannon Holsinger Sep 16 '16 at 19:01
  • 1
    The seed is just...the seed - how the algorithm is initialized. `Next` will give you different numbers, but that sequence would be the same with a new random using the same seed – Ňɏssa Pøngjǣrdenlarp Sep 16 '16 at 19:02
  • 3
    If you want 100 times same number, then why use `Random` class – Mrinal Kamboj Sep 16 '16 at 19:02
  • Yes - the 100 numbers you get will be "random," but they will match every time you start with the same seed. Not x repeated 100 times, but x(1)-x(100) repeated each time For/Next is run – Shannon Holsinger Sep 16 '16 at 19:03
  • 1
    Move `var rand = new Random(0);` into the `for` block and you will see that the same number is produced with every call. – Igor Sep 16 '16 at 19:03
  • Possible duplicate of [Random number generator only generating one random number](http://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number) – Igor Sep 16 '16 at 19:05
  • (on your latest edit) How would that be changing the seed? You hard coded `0` in the constructor?? If you want it as random as possible then do not pass in anything, the system clock will provide a value. – Igor Sep 16 '16 at 19:06
  • AFTEREDIT: because you are only calling NEXT once in your second example - you are re-seeding every loop – Shannon Holsinger Sep 16 '16 at 19:06
  • First example: 1 seed next*100 second example 100 seeds next*1 each seed – Shannon Holsinger Sep 16 '16 at 19:07
  • How is generated next seed? – TheChilliPL Sep 16 '16 at 19:07
  • You should really read the documentation: [System.Random](https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx) – Igor Sep 16 '16 at 19:07
  • This is usually confused the other way around. – IS4 Sep 17 '16 at 01:11

1 Answers1

19

It should not give you 100 same numbers but it should give you exactly the same 100 numbers each time you restart the app.

Seed is used to make random predictable. Imagine multiplayer game where you want something to be random. But you want to make sure that this random behaves the same for each player/client. And seed is the way to go here.

serhiyb
  • 4,753
  • 2
  • 15
  • 24