0

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]];
Domas
  • 39
  • 2
  • 7

4 Answers4

4

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

Paul.s
  • 38,494
  • 5
  • 70
  • 88
2

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?

Community
  • 1
  • 1
user3386109
  • 34,287
  • 7
  • 49
  • 68
1

You can use

BOOl isFound = [_randomQuestionNumberArray containsObject:object];
Hossam Ghareeb
  • 7,063
  • 3
  • 53
  • 64
0
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];
}
Pawan Rai
  • 3,434
  • 4
  • 32
  • 42