Generating random, unique values C#

前端 未结 17 1174
佛祖请我去吃肉
佛祖请我去吃肉 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: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 list = new List{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                shuffler.Shuffle(list);
    
                foreach (int value in list)
                {
                    Console.WriteLine(value);
                }
            }
        }
    
        /// Used to shuffle collections.
    
        public class Shuffler
        {
            /// Creates the shuffler with a  as the random number generator.
    
            public Shuffler()
            {
                _rng = new Random();
            }
    
            /// Shuffles the specified array.
            /// The type of the array elements.
            /// The array to shuffle.
    
            public void Shuffle(IList 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;
        }
    }
    

提交回复
热议问题