I'm trying to create a random number generator and storing it into an array, however I sometimes get duplicates. How do I remove the duplicate from the array and generate a unique number on each run?
You'd need to, after generating a particular index's number, check all previously generated numbers for any matches. Probably a more efficient way to do this, but here's code that would probably work:
for (int i = 0; i < 5; i++)
{
bool isDuplicate;
//generate this number at least once
do {
//generate intial number
num[i] = rand()%50 + 1;
//assume number is unique
isDuplicate = false;
//find case among previously generated numbers where there is a duplicate
for (int j = 0; j < i; ++j)
{
if ( num[i] == num[j] )
{
isDuplicate = true;
break;
}
}
} while ( isDuplicate );
}