This is really weird, and I cannot see why this is happening. In the foreach cycle, I am iterating through a class A collection, and for each class, I call the Count()
method, where r1
and r2
numbers are generated from range [-1,1]. The problem is that Random.Next
returns the same "random" numbers for each instance. When the results for the first instance are 0 and -1, the same ones will be returned from following instances. Please, could you tell me why this is happening? Also, I cannot get different results in each class A instance. This is the code:
class a { Random rnd = new Random(); private void Count() { int r1 = rnd.Next(-1, 1); int r2 = rnd.Next(-1, 1); } } class b { List<a> listofA=new list<a>(); foreach (a ACLASS in listofA) { ACLASS.Count(); } }
Next() Returns a non-negative random integer.
The numbers generated are not truly random; typically, they form a sequence that repeats periodically, with a period so large that you can ignore it for ordinary purposes. The random number generator works by remembering a seed value which it uses to compute the next random number and also to compute a new seed.
Next() Method This method is used to returns a non-negative random integer. Syntax: public virtual int Next (); Return Value: This method returns the 32-bit signed integer which is greater than or equal to 0 and less than MaxValue.
So for instance: random. seed() # you need to seed the random number generator n = random. randint(1, 100) if n < age: print("I am younger than you.") elif n > age: print("I am older than you.") else: print("We are the same age.")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With