Random numbers each .Next () call [Multiple .Next () in the method]

I have a problem with a random number spawning in C #

I tried all the solutions found. In most cases, we use the same random object every time only every object works, and not every property.

So I use this as a code for 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() several times in the same method to create 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); } } 

Each new object gets a different number, but not every time I call the Next() method.

Thus, all property values ​​become the same for 1 object.

How can i fix this? Why don't I get a new value with every call to .Next() ?

thanks

Bye!

+4
source share
3 answers

Random.Next(0, 1) will always return 0 . The maximum value is exclusive.

+4
source

Due to the pigeonhole principle, it is difficult to obtain 5 different integer values ​​ranging from [0-4).

Since the numbers are random, you should expect that there will be a number of cases where all values ​​will be the same.

(in addition to the error identified by @IngisKahn using Random.Next(0,1) )

+2
source

Try

 return (random.Next() % (max - min)) + min 
0
source

All Articles