当前位置 > 首页 > Asp.net

How to pick numbers at random from a given set of numbers in c#

2009-10-1 20:33:00来源:Asp.net

The Random class defined in the .NET Framework provides functionality to generate pseudo-random number. According to MSDN, the current implementation of the Random class is based on Donald E. Knuth's subtractive random number generator algorithm. The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random.

However, current implementation does not provide the following two functionalities.

  1. Picking random numbers from a given set of numbers: For example, you want random number from the given set of numbers. You have a set of numbers like (2, 4, 13, and 21).You would like to pick one number at a time at random from the list.
  2. Picking random numbers from a range of numbers with no repetition: Current implementation return random numbers within a range with some duplicate number. For example, you want random number from a range of numbers like (4 to 21). You would like to pick one number at a time at random from that range without any repetition or duplicate

However, these two requirements are easy to implement by using the Random class of the .NET Framework. I needed these two functionalities for one of my project, so I wrote a class to implement these two features. I think that this is a trivial work but I am posting it because it can save some of your time. To implement these two functionalities following class named RandomNumberFromAGivenSetOfNumbers is written.

   1: class RandomNumberFromAGivenSetOfNumbers
   2:    {
   3:        List<int> _setOfNumbers = new List<int>();
   4:  
   5:        public List<int> SetOfNumbers
   6:        {
   7:            get { return _setOfNumbers; }