Random Number In C #

Possible duplicate:
The random number generator does not work as I planned (C #)

I created a method that returns me a random number:

public static int SelectRandomMachine(int max) { int seed = (int)DateTime.Now.Ticks; Random rndNumber = new Random(seed); int randMachine = rndNumber.Next(0, max); return randMachine; } 

if I call the method twice, it currently returns me the same random number:

 randM1 = SelectRandomMachine(maxNumber); randM2 = SelectRandomMachine(maxNumber); 

Any suggestion would be highly appreciated.

+3
source share
5 answers

Tell this line:

 int seed = (int)DateTime.Now.Ticks; 

If you run this line twice in a row, what do you think the values ​​will be?

For example:

 int seed1 = (int)DateTime.Now.Ticks; int seed2 = (int)DateTime.Now.Ticks; // Write it out *after* executing; console output can take a while Console.WriteLine(seed1); Console.WriteLine(seed2); 

See my article an article on randomness for a solution and more information.

EDIT: here's a quick and dirty example of thread insecurity causing problems:

 using System.Collections.Generic; using System.Threading; class Program { const int Iterations = 1000000; static readonly Random rng = new Random(); static void Main(string[] args) { List<Thread> threads = new List<Thread>(); for (int i = 0; i < 8; i++) { Thread t = new Thread(ExerciseRandom); threads.Add(t); t.Start(); } foreach (Thread t in threads) { t.Join(); } Console.WriteLine(rng.Next()); Console.WriteLine(rng.Next()); Console.WriteLine(rng.Next()); } static void ExerciseRandom() { for (int i = 0; i < Iterations; i++) { rng.Next(); } } } 

The output in my field is:

 0 0 0 
+6
source

You need to create one instance of the Random object and call it several times.

Since you base your seed on time (number of ticks), quick calls in a row will generate the same initial value, so the pseudo-random number generator will generate the same sequence.

+2
source

Make the Random instance random:

 static Random rndNumber = new Random((int)DateTime.Now.Ticks); public static int SelectRandomMachine(int max) { int randMachine = rndNumber.Next(0, max); return randMachine; } 
+1
source

You need to have a private static Random () and refer to it to get random numbers, Jon and Oded are right, you cannot call fast.

 private static Random _rnd = new Random(); public static int SelectRandomMachine(int max) { //int seed = (int)DateTime.Now.Ticks; //Random rndNumber = new Random(seed); int randMachine = _rnd.Next(0, max); return randMachine; } 
0
source

Random number generators generate numbers using an algorithm. If you seed an algorithm with the same number, it will generate the same sequence of numbers. This means that every time you seed a rand with a number, and then pull out the first number of the sequence, you will always get the same number. You need to split rand once and then use Next() several times on the same Rand object.

0
source

All Articles