random number generation:returning same number in C# if I run. alright if Debug step by step
Don't instantiate a new Random
object each time, instead use it as a static
member:
class Greyhound
{
static Random randomize = new Random();
int location=0;
public int run()
{
location = randomize.Next(0, 100);
return location;
}
}
See Random.Next returns always the same values
You are creating x amount of new Random at the same time.
what you should do is create new instance of Random and then inside foreach (or any loop) use instance.Next().
That should give you the unique values.
Hope it helps
your answer is here: Random Constructor
The distribution of the generated numbers is uniform; each number is equally likely to be returned.
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.
you create all those Random
objects basically at the same time in the loop and all are initialized with same time dependent seed, try to create only one static object or specify the seed differently. in debug the waiting time of you moving line by line already makes the seed to be different.