Unique random numbers in C#

假装没事ソ 提交于 2019-12-11 17:57:46

问题


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();

回答1:


There are mainly three approaches that are used to get random numbers without collisions:

  1. Keep all numbers that you have picked, so that you can check a new number against all previous.
  2. Create a range of unique numbers, shuffle them, and pick one at a time from the result.
  3. 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.




回答2:


You could use the Random class and a HashSet which will guarantee no duplicate items.

The HashSet class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

E.g:

HashSet<int> t = new HashSet<int>();
Random r = new Random();

while(t.Count < 50)//or the desired length of 't'
{
    t.Add(r.Next(0,1000));//adjust min/max as needed
}

foreach (int i in t)
{
    Console.WriteLine(i);
}
Console.Read();

Will give you a collection of 50 guaranteed unique random integers.

Since the number of elements in the set is not a requirement for this question it seems irrelevant to even mention, though if this is a requirement you can simply modify the line t.Count < ? to get a set of a desired length.




回答3:


You could use Guid.NewGuid() or new Random().Next()




回答4:


Assuming that you want unique numbers in a limited range, one (simple but possibly inefficient) way to do it is to create a list of all possible values (say, 0-99). Then you use System.Random to pick a random between 0 and (number of elements in list - 1). Get that index from the list, output it and remove the element. If you repeat the process, that element can no longer be generated and the numbers will be unique until you've used all possible values.




回答5:


Create one instance of Random class. Make sure it is one!

then use this code

private Random random = new Random();

random.Next();


来源:https://stackoverflow.com/questions/16057488/unique-random-numbers-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!