Hi there, I trying to fill an array of 20 ints with numbers from 1-20 in random sequence. here's my code:
int lookup[20]={0};
int array[20]={0};
srand(time(NULL));
for(int i=0;i<20;++i){
bool done=false;
while(!done){
int n=rand()%20;
if(lookup[n]==0){
array[i]=n;
lookup[n]=1;
done=true;
}
}
}
I've created a lookup array to check if the random number is not yet chosen and stored it in array. As you can see I've created 2 loops, one for traversing array and the while for choosing the random number. In every while loop iteration the number may reappear and causing another while loop. Is there faster way to do this?