2

我在历史板上创建了 10 个 UIButton,好吗?
我想添加不重复这些数字的随机数,即在加载视图时穿插的从 0 到 9 的数字。

我试图在谷歌和这里找到一种使用我现有按钮(10 UIButton)的方法,并将它们应用于随机值​​。找到的大多数方法 ( arc4random() % 10),重复数字。

所有结果发现动态创建按钮。有人经历过吗?

4

2 回答 2

2

创建一个数字数组。然后对数组中的元素执行一组随机交换。您现在拥有以随机顺序排列的唯一编号。

- (NSArray *)generateRandomNumbers:(NSUInteger)count {
    NSMutableArray *res = [NSMutableArray arrayWithCapacity:count];
    // Populate with the numbers 1 .. count (never use a tag of 0)
    for (NSUInteger i = 1; i <= count; i++) {
        [res addObject:@(i)];
    }

    // Shuffle the values - the greater the number of shuffles, the more randomized
    for (NSUInteger i = 0; i < count * 20; i++) {
        NSUInteger x = arc4random_uniform(count);
        NSUInteger y = arc4random_uniform(count);
        [res exchangeObjectAtIndex:x withObjectAtIndex:y];
    }

    return res;
}

// Apply the tags to the buttons. This assumes you have 10 separate ivars for the 10 buttons
NSArray *randomNumbers = [self generateRandomNumbers:10];
button1.tag = [randomNumbers[0] integerValue];
button2.tag = [randomNumbers[1] integerValue];
...
button10.tag = [randomNumbers[9] integerValue];
于 2013-03-02T23:07:26.520 回答
1

@meth 有正确的想法。如果您想确保数字不重复,请尝试以下操作:(注意:顶部将生成最高数字。确保此 => 数量,否则这将永远循环;)

- (NSArray*) makeNumbers: (NSInteger) amount withTopBound: (int) top
{ 
     NSMutableArray* temp = [[NSMutableArray alloc] initWithCapacity: amount];

     for (int i = 0; i < amount; i++)
     {
        // make random number
        NSNumber* randomNum; 

        // flag to check duplicates
        BOOL duplicate;

        // check if randomNum is already in your array
        do
        {
            duplicate = NO;
            randomNum = [NSNumber numberWithInt: arc4random() % top];

            for (NSNumber* currentNum in temp)
            {
                if ([randomNum isEqualToNumber: currentNum])
                {
                    // now we'll try to make a new number on the next pass
                    duplicate = YES;
                }
            }
        } while (duplicate)

        [temp addObject: randomNum];
    }

    return temp;
}
于 2013-03-02T22:29:51.710 回答