Generating random, unique values C#

前端 未结 17 1154
佛祖请我去吃肉
佛祖请我去吃肉 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<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();
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 15:12

    I'm posting a correct implementation of a shuffle algorithm, since the other one posted here doesn't produce a uniform shuffle.

    As the other answer states, for small numbers of values to be randomized, you can simply fill an array with those values, shuffle the array, and then use however many of the values that you want.

    The following is an implementation of the Fisher-Yates Shuffle (aka the Knuth Shuffle). (Read the "implementation errors" section of that link (search for "always selecting j from the entire range of valid array indices on every iteration") to see some discussion about what is wrong with the other implementation posted here.)

    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;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 15:12

    Depending on what you are really after you can do something like this:

    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;
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 15:15

    This console app will let you shuffle the alphabet five times with different orders.

    using System;
    using System.Linq;
    
    namespace Shuffle
    {
        class Program
        {
            static Random rnd = new Random();
            static void Main(string[] args)
            {
                var alphabet = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
                Console.WriteLine("Alphabet : {0}", string.Join(",", alphabet)); 
                for (int i = 0; i < 5; i++)
                {
                    var shuffledAlphabet = GetShuffledAlphabet(alphabet);
                    Console.WriteLine("SHUFFLE {0}: {1}", i, string.Join(",", shuffledAlphabet));
                }
            }
    
            static string[] GetShuffledAlphabet(string[] arr)
            {
                int?[] uniqueNumbers = new int?[arr.Length];
                string[] shuffledAlphabet = new string[arr.Length];
    
                for (int i = 0; i < arr.Length; i++)
                {
                    int uniqueNumber = GenerateUniqueNumber(uniqueNumberArrays);
                    uniqueNumberArrays[i] = uniqueNumber;
                    newArray[i] = arr[uniqueNumber];
                }
    
                return shuffledAlphabet;
            }
    
            static int GenerateUniqueNumber(int?[] uniqueNumbers)
            {
                int number = rnd.Next(uniqueNumbers.Length);
    
                if (!uniqueNumbers.Any(r => r == number))
                {
                    return number;
                }
    
                return GenerateUniqueNumber(uniqueNumbers);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 15:15

    randomNumber function return unqiue integer value between 0 to 100000

      bool check[] = new bool[100001];
      Random r = new Random();
      public int randomNumber() {
          int num = r.Next(0,100000);
           while(check[num] == true) {
                 num = r.Next(0,100000);
         }
        check[num] = true;
       return num;
     }
    
    0 讨论(0)
提交回复
热议问题