1

这就是我想要做的。每次我的 viewDidLoad 启动时获取 7 个随机的、非重复的数字。我得到它来创建随机数,但我一直试图在加载 NSMutableSet 以获取新集合时清除它,但我遇到了麻烦。NSLog 清楚地显示 NSMutableSet 中没有任何内容,但它总是以相同的顺序出现相同的数字?

// Create set
NSMutableSet *mySet = [NSMutableSet setWithCapacity:6];

// Clear set
NSMutableSet *mutableSet = [NSMutableSet setWithSet:mySet];
[mutableSet removeAllObjects];
mySet = mutableSet;

NSLog(@"mutableSet: %@", mutableSet);  // Shows nothing
NSLog(@"mySet: %@", mySet);  // Shows nothing

// Assign random numbers to the set
while([mySet count]<=6){
    int Randnum = arc4random() % 7+1;
    [mySet addObject:[NSNumber numberWithInt:Randnum]];
}

NSLog(@"mySet1: %@", mySet);  // Always shows 5,1,6,2,7,3,4 ???
4

1 回答 1

1

AnNS(Mutable)Set是一个无序集合,它不会保留插入元素时的顺序。因此,您的输出仅显示该集合包含从 1 到 7 的数字。

您有不同的选择来获得预期的输出。

  1. 改用一个NSMutableOrderedSet

  2. 使用集合来跟踪已经发生的数字,但也将数字存储在数组中:

    NSMutableArray *numbers = [NSMutableArray array];
    NSMutableSet *mySet = [NSMutableSet set];
    while ([numbers count] < 6) {
        NSNumber *randNum = @(arc4random_uniform(7) + 1);
        if (![mySet containsObject:randNum]) {
            [numbers addObject:randNum];
            [mySet addObject:randNum];
        }
    }
    NSLog(@"numbers: %@", numbers);
    
  3. 对于一个小集合(如您的情况下的 7 个数字),您可以只使用一个数组:

    NSMutableArray *numbers = [NSMutableArray array];
    while ([numbers count] < 6) {
        NSNumber *randNum = @(arc4random_uniform(7) + 1);
        if (![numbers containsObject:randNum]) {
            [numbers addObject:randNum];
        }
    }
    NSLog(@"numbers: %@", numbers);
    
于 2014-09-12T20:31:12.677 回答