简体   繁体   English

如何检查NSMutableArray中是否已经存在一个值?

[英]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]];

Sounds like a perfect use case for an NSMutableOrderedSet If ordering is not important then NSMutableSet is your best bet 听起来像是NSMutableOrderedSet的完美用例如果订购不重要,那么NSMutableSet是最好的选择


You should also be using arc4random_uniform instead of arc4random % to reduce modulo bias 您还应该使用arc4random_uniform而不是arc4random %来减少模偏差

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? 请参见洗牌NSMutableArray的最佳方法是什么?

您可以使用

BOOl isFound = [_randomQuestionNumberArray containsObject:object];
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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM