生成随机的,唯一的值C#

我search了一段时间,一直在努力寻找这个,我试图生成几个随机的,唯一的数字是C#。 我正在使用System.Random,并使用datetime.now.ticks种子:

public Random a = new Random(DateTime.Now.Ticks.GetHashCode()); private void NewNumber() { MyNumber = a.Next(0, 10); } 

我经常打电话给NewNumber(),但问题是我经常得到重复的数字。 有人build议,因为我每次做的时候都是随机的,不会产生一个随机数,所以我把这个声明放在我的函数之外。 任何build议或更好的方法比使用System.Random? 谢谢

我经常打电话给NewNumber(),但问题是我经常得到重复的数字。

Random.Next不保证数字是唯一的。 此外,您的范围是从0到10,您可能会得到重复值。 可能是你可以设置一个int列表并在列表中插入随机数字后检查它是否不包含重复。 就像是:

 public Random a = new Random(); // replace from new Random(DateTime.Now.Ticks.GetHashCode()); // Since similar code is done in default constructor internally public List<int> randomList = new List<int>(); int MyNumber = 0; private void NewNumber() { MyNumber = a.Next(0, 10); if (!randomList.Contains(MyNumber)) randomList.Add(MyNumber); } 

如果您的范围只有0到9,您可以尝试对一系列可能的整数进行混洗。这增加了避免编号产生冲突的好处。

 var nums = Enumerable.Range(0, 10).ToArray(); var rnd = new Random(); // Shuffle the array for (int i = 0;i < nums.Length;++i) { int randomIndex = rnd.Next(nums.Length); int temp = nums[randomIndex]; nums[randomIndex] = nums[i]; nums[i] = temp; } // Now your array is randomized and you can simply print them in order for (int i = 0;i < nums.Length;++i) Console.WriteLine(nums[i]); 

我正在发布shufflealgorithm的正确实现,因为在这里发布的另一个不会产生统一的洗牌。

正如其他答案所述,对于less量的随机数值,您可以简单地使用这些值填充一个数组,随机数组,然后使用所需的许多值。

以下是Fisher-Yates Shuffle (又名Knuth Shuffle)的实现。 (阅读该链接的“实现错误”部分(search“每次迭代时总是从有效数组索引的整个范围中selectj”),以查看关于此处发布的其他实现的错误的一些讨论。

 using System; using System.Collections.Generic; namespace ConsoleApplication2 { static class Program { static void Main(string[] args) { Shuffler shuffler = new Shuffler(); List<int> list = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; shuffler.Shuffle(list); foreach (int value in list) { Console.WriteLine(value); } } } /// <summary>Used to shuffle collections.</summary> public class Shuffler { /// <summary>Creates the shuffler with a <see cref="MersenneTwister"/> as the random number generator.</summary> public Shuffler() { _rng = new Random(); } /// <summary>Shuffles the specified array.</summary> /// <typeparam name="T">The type of the array elements.</typeparam> /// <param name="array">The array to shuffle.</param> public void Shuffle<T>(IList<T> array) { for (int n = array.Count; n > 1; ) { int k = _rng.Next(n); --n; T temp = array[n]; array[n] = array[k]; array[k] = temp; } } private System.Random _rng; } } 

注意,我不推荐这个:)。 这里还有一个“oneliner”:

 //This code generates numbers between 1 - 100 and then takes 10 of them. var result = Enumerable.Range(1,101).OrderBy(g => Guid.NewGuid()).Take(10).ToArray(); 

你可以做这样的事情后,根据你真的是什么:

 using System; using System.Collections.Generic; using System.Linq; namespace SO14473321 { class Program { static void Main() { UniqueRandom u = new UniqueRandom(Enumerable.Range(1,10)); for (int i = 0; i < 10; i++) { Console.Write("{0} ",u.Next()); } } } class UniqueRandom { private readonly List<int> _currentList; private readonly Random _random = new Random(); public UniqueRandom(IEnumerable<int> seed) { _currentList = new List<int>(seed); } public int Next() { if (_currentList.Count == 0) { throw new ApplicationException("No more numbers"); } int i = _random.Next(_currentList.Count); int result = _currentList[i]; _currentList.RemoveAt(i); return result; } } } 

您也可以使用存储每个随机值的dataTable,然后只需在dataColumn中的!=值时执行随机方法

在这里我的版本使用HashSetfindN个随机唯一的数字。 看起来很简单,因为HashSet只能包含不同的项目。 这很有趣 – 使用List或Shuffler会更快吗?

 using System; using System.Collections.Generic; namespace ConsoleApplication1 { class RnDHash { static void Main() { HashSet<int> rndIndexes = new HashSet<int>(); Random rng = new Random(); int maxNumber; Console.Write("Please input Max number: "); maxNumber = int.Parse(Console.ReadLine()); int iter = 0; while (rndIndexes.Count != maxNumber) { int index = rng.Next(maxNumber); rndIndexes.Add(index); iter++; } Console.WriteLine("Random numbers were found in {0} iterations: ", iter); foreach (int num in rndIndexes) { Console.WriteLine(num); } Console.ReadKey(); } } } 

您可以使用C#的基本随机函数

 Random ran = new Random(); int randomno = ran.Next(0,100); 

你现在可以使用任意值的randomno中的值,但是请记住,这将产生一个介于0100之间的随机数,并且你可以将其扩展到任何数字。

尝试这个:

 private void NewNumber() { Random a = new Random(Guid.newGuid().GetHashCode()); MyNumber = a.Next(0, 10); } 

一些说明:

Guid : 基于此 :表示全局唯一标识符(GUID)

Guid.newGuid()生成一个唯一的标识符,如"936DA01F-9ABD-4d9d-80C7-02AF85C822A8"

在这里的宇宙基础上将是唯一的

哈希码在这里产生一个唯一的整数从我们的唯一标识符

所以Guid.newGuid().GetHashCode()给我们一个唯一的数字,随机类将产生真正的随机数字抛出