# Generating random numbers WITHOUT duplicates

• 02-09-2002
fake1
Generating random numbers WITHOUT duplicates
How can I generate random numbers without duplicates assuming I have a function that will generate random integers from x to y inclusive.

Thanks.
• 02-09-2002
Sorensen
Keep a record of all previous random numbers and reject any new random numbers that match one of these.
• 02-09-2002
Stoned_Coder
To add to what sorenson said. A binary tree will allow you to do this quickly. Call rand in a loop and pass the output to your binary tree insert func which you have coded to reject duplicates. End the loop when the tree contains the right number of values. You could also use stl set or stl map to do this if that sounds like too much work for you.
• 02-09-2002
samGwilliam
If you can't be arsed to code a binary tree class then: if you know how many numbers you need, create an array of that size and fill it with 1, 2, 3... and swap random pairs a few thousand times (trivial for a PC). For more variety instead of having each slot one greater than the last make it a random amount bigger. Like:

Code:

``` void swap (int *one, int *two); void main (void) {   int i;   int num [20];   int newNum = 1;   int swapOne;   int swapTwo;     for (i = 0; i < 20; i++)   {       num [i] = newNum;       newNum += (random (5));   }   for (i = 0; i < 9000; i++)   {       swapOne = random (20);       do       {           swapTwo = random (20);       } while (swapTwo == swapOne);  // Avoid duplicates.       swap (num + swapOne, num + swapTwo);  // Or use &num [swapOne], etc.   } } void swap (int *one, int *two) {   int temp = *one;   *one = *two;   *two = temp; }```
If you have no random () function (like MSVC). The definition is as follows:

Code:

```int random (int r) {   return (rand () % r); }```