Reputation: 99
I have a problem with random number generating in C#
I have tried all the solutions that I've found. Most we're only using the same random object every time which works only each object, not each property.
So I am using this as code for the random numbers:
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public static int RandomNumber(int min, int max)
{
lock (syncLock)
{ // synchronize
return random.Next(min, max);
}
}
Now I want to call .Next()
multiple times in the same method, to generate a random object:
public void StartDuiven()
{
for (int i = 0; i <= 6; i++)
{
var d = new Duif();
d.Naam = /*NameGenerator.GenRandomFirstName() +" "+ NameGenerator.GenRandomLastName()*/ "Jantje";
d.GeboorteDatum = DateTime.Now;
d.Snelheid = Genrator.RandomNumber(0, 4);
d.Vliegtechniek = Genrator.RandomNumber(0, 4);
d.Vormpeil = Genrator.RandomNumber(0, 4);
d.Conditie = Genrator.RandomNumber(0, 4);
d.Aerodynamica = Genrator.RandomNumber(0, 4);
d.Intelligentie = Genrator.RandomNumber(0, 4);
d.Libido = Genrator.RandomNumber(0, 4);
d.Nachtvliegen = Genrator.RandomNumber(0, 4);
d.Navigatie = Genrator.RandomNumber(0, 4);
d.Ervaring = Genrator.RandomNumber(0, 4);
d.Transfer = false;
int g = Genrator.RandomNumber(0, 2); // Edited
if (g == 0)
d.Geslacht = false;
else
d.Geslacht = true;
AddDuif(d);
}
}
Every new object I get a different number, but not every time I call .Next()
method.
So all the values of the properties become the same for 1 object.
How could I fix this? Why don't I get a new value on each .Next()
call?
Thank you
Bye!
Upvotes: 4
Views: 196
Reputation: 100547
Due to pigeonhole principle it is hard :) to get 5 distinct integer value in range of [0-4).
Since numbers are random you should expect that there will be some number of cases when all values will be the same.
(in addition to bug identified by @IngisKahn with usage of Random.Next(0,1)
)
Upvotes: 2
Reputation: 869
Random.Next(0, 1)
will always return 0
. The max value is exclusive.
Upvotes: 4