C#中產生唯一隨機值的有效方法
在許多程式設計場景中,產生唯一的隨機數是一個常見需求。然而,使用預設的System.Random
類別並不能保證唯一性,尤其是在範圍較小的情況下。
Random.Next() 的限制
Random.Next()
方法並非設計用於在給定範圍內產生唯一值。它在指定範圍內產生隨機整數,並且可能產生重複的數字,尤其是在範圍較小的情況下。
使用種子值
使用種子值,例如DateTime.Now.Ticks.GetHashCode()
,是提高Random
類隨機性的常用方法。但是,它仍然不能消除產生重複數字的可能性。
更優的方案
與其依賴Random.Next()
,不如考慮使用以下方法來產生唯一的隨機數:
<code class="language-csharp">public class RandomGenerator { private readonly Random _random; private HashSet<int> _uniqueValues; public RandomGenerator() { _random = new Random(); _uniqueValues = new HashSet<int>(); } public int GetUniqueNumber(int min, int max) { int randomNumber; do { randomNumber = _random.Next(min, max); } while (_uniqueValues.Contains(randomNumber)); _uniqueValues.Add(randomNumber); return randomNumber; } }</code>
這種方法使用HashSet
來儲存已產生的數值。 GetUniqueNumber
方法會重複產生隨機數,直到在指定範圍內找到一個唯一的值為止。這確保了唯一性,同時仍然使用了Random
類別。
以上是如何在 C# 中產生真正唯一的隨機數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!