2014-02-09 94 views
1

我试图在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:..]之前的某种循环,以便当我在标签中显示数字他们是独特的?先谢谢你!

哈利

+1

只是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

回答

2

由于int S的顺序并不重要(它们是随机的,反正)与NSMutableSet更换NSMutableArray容器将让你避免重复。所有你现在需要做的是检查容器的大小,当你到达四个所需的大小停止:

NSMutableSet *theSequence = [NSMutableSet set]; 

do { 
    int r = arc4random()%12 + 1; 
    [theSequence addObject:[NSNumber numberWithInteger:r]]; 
} while (theSequence.count != difficultyLevel); 

注:如果由于某种原因插入顺序很重要,你可以使用NSMutableOrderedSet

+0

如果顺序很重要,OP可以简单地使用'NSMutableOrderedSet'顺便说一句。 –

+0

@David谢谢,大卫!这是一个非常好的评论。 – dasblinkenlight

+0

@dasblinkenlight就像一个魅力,你绝对的明星! :) – Xaser3