Random number generator always picks the same value when run inside a loop

后端 未结 5 882
慢半拍i
慢半拍i 2020-11-30 14:15

The problem with the code is, when I try to generate a number, if the spin is equal 1 it generates values inside range (1,2,3) if if try to use the loop to sum random values

相关标签:
5条回答
  • 2020-11-30 14:50

    You are probably creating a new Random object inside RandomNumber method. The default constructor for Random uses the system time as a seed. If you create multiple Random objects in a tight loop the time probably won't have changed between each call so they will all be initialized with the same seed.

    To fix your code you should only create one Random object and reuse it.


    From the documentation:

    The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers. You can also work around it by modifying the seed value returned by the system clock and then explicitly providing this new seed value to the Random(Int32) constructor. For more information, see the Random(Int32) constructor.

    0 讨论(0)
  • 2020-11-30 14:55

    You can use Random(seed) constructor.

    Random rand = new Random(Guid.NewGuid().GetHashCode());
    
    0 讨论(0)
  • 2020-11-30 15:03

    The problem is that you are creating random generators too close in time. The random generator constructor uses the current time to seed the generator, and when you create them too close in time they will all be seeded using the same time.

    Create one random generator and use in the loop:

    Random rnd = new Random();
    for (int i = 1; i <= spind3.Value; i++) {
      diceCalc[1] += rnd.Next(1, 4);
    }
    
    0 讨论(0)
  • 2020-11-30 15:11

    You need to initialize your Random object, then call Next() inside your loop.

    i.e.

    if (toggled3.Checked)
    {
      // initialize your total and the random number generator
      int diceTotal = 0;
      Random rand = new Random();
    
      for (int i = 0; i < spind3.Value; i++)
      {
        // add the next random number between 1 and 3
        diceTotal += rand.Next(1, 4); 
      }
    }
    
    0 讨论(0)
  • 2020-11-30 15:14

    One trick is to manually create the seed by adding DateTime.Now.Ticks to the variable i:

    Random r = new Random((int)DateTime.Now.Ticks + i);
    
    0 讨论(0)
提交回复
热议问题