Domas
Domas

Reputation: 39

How to check is a value already exist in NSMutableArray?

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

Answers (4)

Paul.s
Paul.s

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

Pawan Rai
Pawan Rai

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

user3386109
user3386109

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

Hossam Ghareeb
Hossam Ghareeb

Reputation: 7123

You can use

BOOl isFound = [_randomQuestionNumberArray containsObject:object];

Upvotes: 1

Related Questions