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!
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>
constint AMOUNT; //amount of random numbers that need to be generated
constint 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
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