Generating random, unique values C#

前端 未结 17 1158
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 14:26

I\'ve searched for a while and been struggling to find this, I\'m trying to generate several random, unique numbers is C#. I\'m using System.Random, and I\'m us

17条回答
  •  名媛妹妹
    2020-11-22 15:11

    And here my version of finding N random unique numbers using HashSet. Looks pretty simple, since HashSet can contain only different items. It's interesting - would it be faster then using List or Shuffler?

    using System;
    using System.Collections.Generic;
    
    namespace ConsoleApplication1
    {
        class RnDHash
        {
            static void Main()
            {
                HashSet rndIndexes = new HashSet();
                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();
            }
        }
    }
    

提交回复
热议问题