C# - Random number with seed

18,753

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.

Share:
18,753
TheChilliPL
Author by

TheChilliPL

Updated on July 22, 2022

Comments

  • TheChilliPL
    TheChilliPL almost 2 years

    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
    TheChilliPL over 7 years
    Seed is increasing or what?
  • serhiyb
    serhiyb over 7 years
    Seed defines sequence of random number that will be generated. The same sequence is generated for the same seed.
  • TheChilliPL
    TheChilliPL over 7 years
    Ok, I understand. Thanks for help
  • TheChilliPL
    TheChilliPL over 7 years
    I have last question - is this sequence repeatable or infinite? I mean if I will call "Next(0, 100)" many times, will sequence go again from start? (Sorry for my English)
  • Marc Gravell
    Marc Gravell over 7 years
    @TheChilliPL it shouldn't, basically; although that is not a strict guarantee. It is not an inbuilt expectation that it should restart unless you create a new Random with the original seed
  • TheChilliPL
    TheChilliPL over 7 years
    Thanks for help :)
  • TheChilliPL
    TheChilliPL over 7 years
    I have another question - can I find nth random number from seed?