Urgent: Generating random numbers WITHOUT repetition

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!
Create an array to store the random numbers in, and before you use a number, check or it already is used.
Last edited on
Is impossible having perfect random number with an algorithm, you can only have pseudo random number generators

http://en.wikipedia.org/wiki/PRNG
ok. thank you!
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>
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
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 
i got it! thank you very much!
Last edited on
//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.