Your random number generator (RNG) appears to be generating only a single unique number despite using a loop. Debugging reveals different numbers during loop execution, but upon completion, all array elements hold the same value.
The problem stems from creating a new Random
instance within each loop iteration. Since Random
is often seeded using the system clock, a rapidly executed loop may repeatedly initialize the Random
object with the same seed, leading to identical outputs.
The fix involves using a single, static Random
instance across all calls. This ensures consistent state updates and prevents repeated seed values. To handle multi-threaded scenarios safely, a lock is employed to synchronize access.
Here's the corrected RandomNumber
function:
<code class="language-csharp">private static readonly Random random = new Random(); private static readonly object syncLock = new object(); public static int RandomNumber(int min, int max) { lock (syncLock) { // Thread-safe access return random.Next(min, max); } }</code>
By using a single random
instance and synchronizing access with lock
, the RNG will maintain its internal state, producing unique random numbers on each call within the loop.
The above is the detailed content of Why Does My Random Number Generator Only Produce One Unique Number?. For more information, please follow other related articles on the PHP Chinese website!