Urgent: Generating random numbers WITHOUT repetition

Feb 14, 2009 at 6:26pm
Hello.
May I know how to generate random numbers where all the numbers are different, without repetition? I am using randomize() and rand().
Thank you!
Feb 14, 2009 at 6:41pm
Create an array to store the random numbers in, and before you use a number, check or it already is used.
Last edited on Feb 14, 2009 at 6:42pm
Feb 14, 2009 at 6:46pm
Is impossible having perfect random number with an algorithm, you can only have pseudo random number generators

http://en.wikipedia.org/wiki/PRNG
Feb 15, 2009 at 5:13am
ok. thank you!
Feb 15, 2009 at 6:02am
With rand use - srand((unsigned)time(NULL)); at the start of your main as well. This will allow rand to be more random depending on the time of the system tray clock. And make sure you #include <time.h>
Feb 15, 2009 at 6:14pm
yes, i included time.h

about using array to check, i am not sure about the implementation, can anyone please assist me further? thank you!
Last edited on Feb 15, 2009 at 6:20pm
Feb 15, 2009 at 6:42pm
Normally we don't give code away, but in this case it's easier to show then to explain, so it's your lucky day ;)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const int AMOUNT; //amount of random numbers that need to be generated
const int MAX; //maximum value (of course, this must be at least the same as AMOUNT;

int value[AMOUNT]; //array to store the random numbers in

srand(time(NULL)); //always seed your RNG before using it

//generate random numbers:
for (int i=0;i<AMOUNT;i++)
{
    bool check; //variable to check or number is already used
    int n; //variable to store the number in
    do
    {
    n=rand()%MAX;
    //check or number is already used:
    check=true;
    for (int j=0;j<i;j++)
        if (n == value[j]) //if number is already used
        {
            check=false; //set check to false
            break; //no need to check the other elements of value[]
        }
    } while (!check); //loop until new, unique number is found
    value[i]=n; //store the generated number in the array
}

//at this point in the program we have an array value[] with a serie of unique random numbers 
Feb 16, 2009 at 3:05am
i got it! thank you very much!
Last edited on Feb 16, 2009 at 6:45am
Feb 16, 2009 at 9:55am
//RANDOMIZE : BY Atul

int n = 10, r, result;
int getRandNum[10];
int arr[10] = {0,1,2,3,4,5,6,7,8,9};//atul;
srand ( time(NULL) );
// generate 10 "unique" values...
for (int x = 0; x < 10; ++x)
{
result = r = 0;
r = rand() % n; // get random number from 0 to n
result = arr[r]; // the sought random no intothing w/ it
getRandNum[x] = arr[result];
arr[r] = arr[n-1]; // replace the generated number
n--; // new count;
}
IN getRandNum you will get 10 different random Numbers
Topic archived. No new replies allowed.