Click here to Skip to main content
15,922,155 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I want to get random numbers from the range 0-8 (for example)
without getting duplicated numbers .
I don't know how is the code has to be but If the numbers are separated in
an array it would be a lot easier for me to gain control over the code.
so what I want is:
example:
range[0-4]
the result:
an array with no duplicated numbers a[3,2,1,0,4]

Thanks in advance.
Posted

You can use the following code

int t = rand.Next(10);
The above code will give the random values between 0 and 10.
Using for loop you can store the value. Similarly you can check the previously stored arrays for uniqueness.

See below example
C#
public static int[] GenerateRandomNumbers()
        {
            //Initialize an integer variable
            int num = 0;
            //Initialize an int temp Array
            int[] tempArr = new int[1001];
            //Initialize an int array
            int[] randomNum = new int[1001];
            //Initialize random Number variable
            Random rnd = new Random();


            //Loop through to store Random Numbers to Array
            for (int i = 0; i <= 1000; i++)
            {

                num = rnd.Next(1, 1000);
                tempArr[i] = num;

                //Insert only if the number is not already in the previouly
                //generated vlaue
                for (int j = 0; j < i; j++)
                {
                    if (tempArr[j] != num)
                    {
                        randomNum[i] = num;
                    }
                }
                //output elements in Array
                Console.WriteLine(num);
            }

            return randomNum;
        }
 
Share this answer
 
Comments
weso_f 15-Jun-11 18:52pm    
thanks ,
as I see the debugger running time isn't stable (it will still run until it finds the different...) but I guess time will be very short because of the short range.
NaveenSoftwares 15-Jun-11 19:04pm    
Yes...:)
Two choices:

1) Initialize the array sequentially: [0,1,2,3,4], then shuffle the array by:

for (int i = 0; i < MAX; i++)
    array[i] = i;

for (int i = 0; i < MAX; i++) {
    int tmp = array[i];
    int r = arc4random() % MAX;
    array[i] = array[r];
    array[r] = tmp;
}


You can shuffle several times if you find it's needed.

2) Or initialize the array randomly but make sure you don't duplicate numbers.

There are several different ways to do that, but the most obvious is just keep an array of booleans to indicate whether a number has been used yet, and keep calling random until you get an answer that isn't yet used. Then put that number in the array and mark it as used in your boolean array.

for (int i = 0; i < MAX; i++) 
   used[i] = false;

for (int i = 0; i < MAX; i++) {

   int r = arc4random() % MAX;
   while (used[r])
      r = arc4random() % MAX;

    array[i] = r;
    used[r] = true;

}


Execution time is a lot longer on this second method since you have to keep calling random until you choose the number you haven't chosen yet (but if your array is small, it will terminate in a fairly short period of time).
 
Share this answer
 
Comments
TRK3 15-Jun-11 18:37pm    
I gave you this in C, rather than C#. I normally write in C++ and didn't realize you'd marked this C# -- but I think you can handle converting it.
weso_f 15-Jun-11 18:56pm    
I liked the first choice it's simple and smart.
so it shuffles well.
Thanks
Use the class System.Random, see http://msdn.microsoft.com/en-us/library/system.random.aspx[^].

Remember: don't do a common fatal mistake: get the class instance only once per you application run time (per Application Domain). Use the method System.Random.Next with the parameter 9.

One of the possible methods to enforce uniqueness:
Create an instance of a dictionary System.Collections.Generic.Dictionary<System.Int32, System.Int32> dictionary; use a newly generated random integer value only if it is not already found in a dictionary, in this case add it to a dictionary. When the Count of dictionary instance reaches the value of 9, you're done. You got your permutation in dictionary.Keys.

If you need an array, copy Keys in some array:
C#
int[] result = new int[dictionary.Keys.Count];
dictionary.Keys.CopyTo(result, 0);
return result;


—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900