Random.Next returns always the same values [duplicate]
The problem is that you are creating instances of the Random
class too close in time.
When you create a Random
object, it's seeded with a value from the system clock. If you create Random
instances too close in time, they will all be seeded with the same random sequence.
Create a single Random
object and pass its reference to the constructor when you create instances of the "a" class, instead of creating one Random
object for each "a" instance.
Use a single, static Random number generator for all instances of the class.
class a
{
private static Random rnd;
static a() {
rnd = new Random();
}
private void Count()
{
int r1 = rnd.Next(-1, 2);
int r2 = rnd.Next(-1, 2);
}
}
Note the change to give you numbers in the range -1,1 rather than -1,0
You're creating new instances of Random
very close together (your loop is very tight) so each instance is effectively using the same seed value.
A better approach would be to create one instance and pass that to your Count
method.
You probably know this next bit, but I'll include it here for completeness:
The MSDN has the details on this, but basically your problem is the Random.Next method you're using generates:
A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.
because of this your calls will return -1 or 0.
You include a random instance for each A instance. It sounds like they're all getting the same default seed value. You probably want to make a static random for all A instances and use it repeatedly, or alternatively provide a seed value to the Random() instance in the A constructor.