Reputation: 1640
I want to generate unique random numbers and add item in function of these random numbers. Here is my code :
The problem is when i verify if the number generated exist in the array with the code results.contains(randomNb)
:
int nbRandom = ui->randoomNumberSpinBox->value();
//nbRandom is the number of the random numbers we want
int i = 1;
int results[1000];
while ( i < nbRandom ){
int randomNb = qrand() % ((nbPepoles + 1) - 1) + 1;
if(!results.contains(randomNb)){
//if randomNb generated is not in the array...
ui->resultsListWidget->addItem(pepoles[randomNb]);
results[i] = randomNb;
//We add the new randomNb in the array
i++;
}
}
Upvotes: 0
Views: 1422
Reputation: 51840
results
is an array. That's a built-in C++ type. It's not a class type and doesn't have methods. So this can't work:
results.contains(randomNb)
You probably want to use a QList instead. Like:
QList<int> results;
Add elements to it with:
results << randomNb;
Also, you have an off-by-one error in the code. You start counting from 1 (i = 1
) instead of 0. This will result in missing the last number. You should change the i
initialization to:
int i = 0;
With the changes, your code would become:
int nbRandom = ui->randoomNumberSpinBox->value();
//nbRandom is the number of the random numbers we want
int i = 0;
QList<int> results;
while ( i < nbRandom ){
int randomNb = qrand() % ((nbPepoles + 1) - 1) + 1;
if(!results.contains(randomNb)){
//if randomNb generated is not in the array...
ui->resultsListWidget->addItem(pepoles[randomNb]);
results << randomNb;
//We add the new randomNb in the array
i++;
}
}
Upvotes: 1