Random Number Generation Issues in Loops
This article addresses a common problem encountered when using Random.Next()
within loops: consecutive iterations producing identical random numbers. The issue often manifests when multiple Random
objects are instantiated in quick succession.
Problem Scenario:
Consider the following code snippet:
<code class="language-csharp">class A { Random rnd = new Random(); public void Count() { int r1 = rnd.Next(-1, 1); int r2 = rnd.Next(-1, 1); // ... further code using r1 and r2 ... } } class B { List<A> listOfA = new List<A>(); public B() { // ... populate listOfA ... foreach (A instance in listOfA) { instance.Count(); } } }</code>
If listOfA
contains multiple instances of class A
, each A
object creates its own Random
instance. Due to the high-speed instantiation, these Random
objects might receive the same seed value (often derived from the system clock), leading to identical random number sequences.
Root Cause:
The problem stems from the default Random
constructor's reliance on the system clock for seeding. If multiple Random
objects are created within a very short timeframe, they receive virtually identical seed values, resulting in identical pseudo-random number generation.
Solution: Single Random Instance
The solution is straightforward: create a single Random
instance and reuse it across all instances of class A
. This ensures that a unique, non-repeating sequence of random numbers is generated.
Here's the corrected code:
<code class="language-csharp">class A { private Random rnd; public A(Random rnd) { this.rnd = rnd; } public void Count() { int r1 = rnd.Next(-1, 1); int r2 = rnd.Next(-1, 1); // ... further code using r1 and r2 ... } } class B { Random rnd = new Random(); List<A> listOfA = new List<A>(); public B() { // ... populate listOfA, passing rnd to the constructor ... foreach (A instance in listOfA) { instance.Count(); } } }</code>
By injecting the single Random
instance (rnd
) into the A
class constructor, we guarantee that all calls to rnd.Next()
draw from the same, properly seeded sequence. This effectively eliminates the generation of duplicate random numbers.
The above is the detailed content of Why Does Random.Next Produce Identical Values in Consecutive Loop Iterations?. For more information, please follow other related articles on the PHP Chinese website!