Generating Random Numbers Using the System.Random Class in C#


This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

Before we dive into the details of the System.Random class, we should talk about randomness in discrete mathematics. The two most common scenarios for generating random numbers are generating integers uniformly between 1 and n and generating real numbers uniformly between 0 and 1. Most random-number-generation algorithms are not influenced by the outside universe; they are inherently pseudorandom: predictable and following a pattern (ideally not an obvious one). You should keep in mind the following two statements on pseudorandomness made by respected computer science masters:

  • "Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin." - John Von Neumann (1951)
  • "Random number generators should not be chosen at random." - Donald Knuth (1986)

Let's go back to our main focus now. We use the System.Random class to produce a random number. System.Random can return both decimal and integer random numbers. In addition, System.Random by design can seed its random number generator with a random value derived from the computer system clock. 

            System.Random rnd = new System.Random(); 

You can initialize the seed with any Int32 value on demand at times when the system clock is not fast enough to refresh or when you need to synchronize your random number generators across a network. This is also the common use of a seed to synchronize two random number generators.

            System.Random rnd = new System.Random((int)DateTime.Now.Ticks);

The Random class includes a series of methods allowing you to retrieve the next number produced by the random number generator. The NextDouble method returns a double random number between 0.0 and 1.0. The Next method returns an integer random number between two integer values. The NextBytes method fills the elements of a specified array of bytes with random numbers. The NextDouble, Next, and NextBytes methods are instance methods; therefore, you must instantiate a System.Random object before using them. 

The Next() method has three overloads: 

        // a positive random number
        public virtual int Next();

        // a positive random number less than the specified maximum
        public virtual int Next(int);

        // a random number within a specified range
        public virtual int Next(int, int );

You can use the Next method overloads as shown in Listing 21.37. 

Listing 21.37: Using the Next Property 

            // any valid integer random number
            Int32 dbl1 = rnd.Next();

            // an integer between 0< and UpperBound where UpperBound + 1 >= 0
            Int32 dbl1 = rnd.Next(UpperBound + 1);

            // an integer between LowerBound< and UpperBound where UpperBound + 1 >= 0
            // and LowerBound <= UpperBound + 1
            Int32 dbl1 = rnd.Next(LowerBound, UpperBound + 1);

Using the NextDouble method of the Random class produces the next pseudorandom double value that is greater than 0.0 and less than 1.0.  

        Double dbl1 = rnd.NextDouble();

The NextBytes method of the Random class produces an array of random bytes with values ranging from 0 to MaxValue (MaxValue = 255). 

            Byte[] mybytes = new Byte[5];
            // mybytes is filled with 5 bytes of random data
            rnd.NextBytes(mybytes);

The program in Listing 21.38 generates unique integer random numbers in the ranges that you send to the application and then displays them on the console

Listing 21.38: Generating Unique Random Numbers with Next(Int32, Int32) 

using System;

class testrandom
{
    public static void Main(string[] args)
    {
        int intno;
        if (args.Length == 0)
        {
            Console.WriteLine("Please enter a parameter eg. unique 5");
            return;
        }
        else
        {
            intno = Int32.Parse(args[0]);
            if (intno < 1)
            {
                // Check to see if user has entered value >= 1
                // because my LowerBound is hardcoded to 1
                Console.WriteLine("Enter value greater than or equal to 1");
                return;
            }
        }
        unique_random generateit = new unique_random();
        generateit.create_random(intno);
    }
}

class unique_random
{
    public void create_random(int passed_intno)
    {
        int LowerBound = 1;
        int UpperBound = passed_intno;
        bool firsttime = true;
        int starti = 0;
        int[] vararray;
        vararray = new int[UpperBound];

        // Random Class used here
        Random randomGenerator = new Random(DateTime.Now.Millisecond);

         do
        {
            int nogenerated = randomGenerator.Next(LowerBound, UpperBound + 1);
            // Note: randomGenerator.Next generates no. to UpperBound - 1 hence +1
            //  i got stuck at this pt & had to use the debugger.

            if (firsttime) // if (firsttime == true)
            {
                vararray[starti] = nogenerated;

                // we simply store the nogenerated in vararray
                firsttime = false;
                starti++;
            }
            else // if (firsttime == false)
            {
                bool duplicate_flag = CheckDuplicate(nogenerated, starti, vararray);
                // call to check in array
                if (!duplicate_flag) // duplicate_flag == false
                {
                    vararray[starti] = nogenerated;
                    starti++;
                }
            }
        } while (starti < UpperBound);

        PrintArray(vararray); // Print the array
    }

    public bool CheckDuplicate(int newrandomNum, int loopcount, int[] function_array)
    {
        bool temp_duplicate = false;

        for (int j = 0; j < loopcount; j++)
        {
            if (function_array[j] == newrandomNum)
            {
                temp_duplicate = true;
                break;
            }
        }
        return temp_duplicate;
    }

    // Print Array
    public static void PrintArray(Array arr)
    {
        Console.Write("{");
        int count = 0;
        int li = arr.Length;

        foreach (object o in arr)
        {
            Console.Write("{0}", o);
            count++;

            //Condition to check whether ',' should be added in printing arrray
            if (count < li)
                Console.Write(", ");
        }
        Console.WriteLine("}");
    }
}

Conclusion

Hope this article would have helped you in understanding generating Random Numbers Using the System.Random Class in C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg
The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.

Up Next
    Ebook Download
    View all
    Learn
    View all