Home

Random Non-Repeating Numbers

 

Introduction

In an assignment, you may need to use a series of random non-repeating numbers. This is an example of how you can generate such a series. The numbers are stored in an ArrayList object:

using System;
using System.Collections;

namespace ConsoleApplication5
{
    class Numbers
    {
        public ArrayList RandomNumbers(int max)
        {
            // Create an ArrayList object that will hold the numbers
            ArrayList lstNumbers = new ArrayList();
            // The Random class will be used to generate numbers
            Random rndNumber = new Random();

            // Generate a random number between 1 and the Max
            int number = rndNumber.Next(1, max + 1);
            // Add this first random number to the list
            lstNumbers.Add(number);
            // Set a count of numbers to 0 to start
            int count = 0;

            do // Repeatedly...
            {
                // ... generate a random number between 1 and the Max
                number = rndNumber.Next(1, max + 1);

                // If the newly generated number in not yet in the list...
                if (!lstNumbers.Contains(number))
                {
                    // ... add it
                    lstNumbers.Add(number);
                }

                // Increase the count
                count++;
            } while (count <= 10 * max); // Do that again

            // Once the list is built, return it
            return lstNumbers;
        }
    }

    class Program
    {
        static int Main()
        {
            Numbers nbs = new Numbers();
            const int Total = 30;
            ArrayList lstNumbers = nbs.RandomNumbers(Total);

            for (int i = 0; i < lstNumbers.Count; i++)
                Console.WriteLine("{0}", lstNumbers[i].ToString());
 
            return 0;
        }
    }
}

Here is an example of running the program:

12
21
14
19
25
23
6
24
18
10
22
5
11
4
13
1
3
9
15
20
16
8
17
26
30
7
28
2
27
29
Press any key to continue . . .

Here is another example of running the program:

7
12
9
3
13
4
26
11
19
16
1
20
30
24
10
5
2
27
17
28
15
23
14
6
8
29
21
22
18
25
Press any key to continue . . .

 

 

Home Copyright 2006 FunctionX, Inc.