我试图在Xcode 5中创建一个NSMutableArray,我随机生成1和12之间的数字并将它们存储为整数。问题有时会产生两次相同的数字,这是不可取的。NSMutableArray存储int无重复
//Load array
NSMutableArray *theSequence = [[NSMutableArray alloc] init];
//Generate the Sequence
for (NSInteger i=0; i < difficultyLevel; i++) {
int r = arc4random()%12 + 1;
//Check here if duplicate exists
[theSequence addObject:[NSNumber numberWithInteger:r]];
}
其中difficultyLevel当前为4,因为应该有4个整数存储。
我已经尝试了其他堆栈溢出没有成功的答案,任何人都可以定制[theSequence addObject:..]之前的某种循环,以便当我在标签中显示数字他们是独特的?先谢谢你!
哈利
只是FYI,你用'arc4random()%12'引入了[modulo bias](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias)。 'arc4random_uniform(12)'是一个更好的选择。见[这里](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/arc4random_uniform.3.html)。 – Manny