Reputation: 39
I'm generating random number and adding it to array. But I don't want duplicates to be there. How do I check if the value already exists in array? Thank you!
int lowerBound = 0;
int long upperBound = numberOfQuestions;
int randomQuestionNumber = lowerBound + arc4random() % (upperBound - lowerBound);
[_randomQuestionNumberArray addObject:[NSDecimalNumber numberWithInt:randomQuestionNumber]];
Upvotes: 0
Views: 250
Reputation: 38728
Sounds like a perfect use case for an NSMutableOrderedSet
If ordering is not important then NSMutableSet
is your best bet
You should also be using arc4random_uniform
instead of arc4random %
to reduce modulo bias
Upvotes: 4
Reputation: 3444
int lowerBound = 0;
int long upperBound = numberOfQuestions;
int randomQuestionNumber = lowerBound + arc4random() % (upperBound - lowerBound);
NSDecimalNumber *currentNumber = [NSDecimalNumber numberWithInt:randomQuestionNumber];
if (![_randomQuestionNumberArray containsObject:num]) {
[_randomQuestionNumberArray addObject:num];
}
Upvotes: 0
Reputation: 34829
The most common approach is simply to fill the array with all possible values and then shuffle the array. See What's the Best Way to Shuffle an NSMutableArray?
Upvotes: 2
Reputation: 7123
You can use
BOOl isFound = [_randomQuestionNumberArray containsObject:object];
Upvotes: 1