Tuesday, October 3, 2017

Creating a list of unique random numbers

Creating a list of unique random numbers

public static List<int> GetUniqueRandomNumbers(int iAmountOfRandomNumbers, int iSmallestNumber, int iBiggestNumber)
        {

            //Create a list of numbers from which the routine
            //shall choose the result numbers
            List<int> lstPossibleNumbers = new List<int>();
            for (int i = iSmallestNumber; i <= iBiggestNumber; i++)
            {
           
                    lstPossibleNumbers.Add(i);
            }


            //Create a list, which shall hold the result numbers
            List<int> lstResultList = new List<int>();

            //Initialize a random number generator
            Random objRand = new Random();

            //For-loop which picks each round a unique random number
            for (int i = 0; i < iAmountOfRandomNumbers; i++)
            {
                //Generate random number
                int randomNumber = objRand .Next(1, lstPossibleNumbers.Count) - 1;
                //Use random number as index for the possible number list
                lstResultList.Add(lstPossibleNumbers[randomNumber]);
                //Remove the chosen result number from possible numbers list
                lstPossibleNumbers.RemoveAt(randomNumber);
            }
            return lstResultList;
        }

No comments:

Post a Comment

Use C# Interactive Window for your coding experiment in Visual Studio

dailydotnettips.com/2016/01/12/use-c-interactive-window-for-your-coding-experiment-in-visual-studio-2015/