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
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 singleRandom
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 theRandom(Int32)
constructor. For more information, see theRandom(Int32)
constructor.
You can use Random(seed)
constructor.
Random rand = new Random(Guid.NewGuid().GetHashCode());
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);
}
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);
}
}
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);