I'm trying to create a binary search tree with unique random numbers. I'm using SortedSet to represent my tree and then I make it into an array and then I use Contains to see if a certain number is in the tree. My problem is that I can't figure out how to get all the random numbers different in a simple way. I used the methods Unik and Nålen_Unik but in this code it only generates 1 number to the array Random random = new Random(); Program Tal = new Program(); string nål = Tal.Nålen_Unik(); string TalIArray = Tal.Unik(); bool found = false; SortedSet<string> Tree = new SortedSet<string>(); for (int x = 0; x < 50000; x++) { Tree.Add(TalIArray); } int y = 0; string[] TreeArray = Tree.ToArray<string>(); while (y < TreeArray.Length) { Console.WriteLine(TreeArray[y]); y = y + 1; } private string Unik() { int maxSize = 4; char[] chars = new char[10000]; string a; a = "0123456789"; chars = a.ToCharArray(); int size = maxSize; byte[] data = new byte[1]; RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider(); crypto.GetNonZeroBytes(data); size = maxSize; data = new byte[size]; crypto.GetNonZeroBytes(data); StringBuilder result = new StringBuilder(size); foreach (byte b in data) { result.Append(chars[b % (chars.Length - 1)]); } return result.ToString(); } private string Nålen_Unik() { int maxSize = 1; char[] chars = new char[62]; string a; a = "0123456789"; chars = a.ToCharArray(); int size = maxSize; byte[] data = new byte[1]; RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider(); crypto.GetNonZeroBytes(data); size = maxSize; data = new byte[size]; crypto.GetNonZeroBytes(data); StringBuilder result = new StringBuilder(size); foreach (byte b in data) { result.Append(chars[b % (chars.Length - 1)]); } return result.ToString(); 解决方案 There are mainly three approaches that are used to get random numbers without collisions:Keep all numbers that you have picked, so that you can check a new number against all previous.Create a range of unique numbers, shuffle them, and pick one at a time from the result.Create such a huge random number that the risk of collisions is so small that it's negligible.The second approach is the same principle as shuffling a deck of cards. The third approach is used when creating a GUID, which is basically a random 128 bit value. 这篇关于C#中的唯一随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-23 14:31