想要生成非重复随机数

时间:2012-12-14 13:26:19

标签: iphone objective-c ios random

  

可能重复:
  Generating non-repeating random numbers

这是我的代码

NSUInteger count = 10;
for (NSUInteger i = 0; i < count; ++i) {
    NSLog(@"%d",NeedRandomNumberWithoutRepeat);
}

这个输出应该是这样的 8 7 9 2 1 4 6 3 五 0 哪个是随机的而不是重复的数字

3 个答案:

答案 0 :(得分:1)

这应该有效:

NSUInteger count = 10;

NSMutableArray *array = [[NSMutableArray alloc]init];
for (NSUInteger i = 0; i < count; ++i) {
    [array addObject:[NSNumber numberWithInt:i]];
}

NSMutableArray *copy = [array mutableCopy];
array = [[NSMutableArray alloc]init];
while ([copy count] > 0)
{
    int index = arc4random() % [copy count];
    id objectToMove = [copy objectAtIndex:index];
    [array addObject:objectToMove];
    [copy removeObjectAtIndex:index];
}

答案 1 :(得分:0)

此答案是我在SO中的answer之一的修改版本。

所以,你可能会在这里找到一些奇怪的东西,但是你可以使用它,因为你的要求是相似的。

int TOTAL_NUMBER=10;
NSMutableArray *alreadyGeneratedNumbers;


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
    alreadyGeneratedNumbers=[NSMutableArray new];
}

-(int)generateRandomNumber{
    int low_bound = 0;
    int high_bound = TOTAL_NUMBER;
    int width = high_bound - low_bound;
    int randomNumber = low_bound + arc4random() % width;

    return randomNumber;
}

- (IBAction)button:(id)sender {
    NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:1];

    BOOL contains=YES;
    while ([shuffle count]<1) {
        NSNumber *generatedNumber=[NSNumber numberWithInt:[self generateRandomNumber]];

        if (![alreadyGeneratedNumbers containsObject:generatedNumber]) {
            [shuffle addObject:generatedNumber];
            contains=NO;
            [alreadyGeneratedNumbers addObject:generatedNumber];
        }
    }

    NSLog(@"shuffle %@",shuffle);
    NSLog(@"Next Batch");

    if ([alreadyGeneratedNumbers count] >= TOTAL_NUMBER) {
        NSLog(@"\nGame over, Want to play once again?");//or similar kind of thing.
        [alreadyGeneratedNumbers removeAllObjects];
    }
}

答案 2 :(得分:-1)

您将可用的数字放在一个数组中,并将使用arc4random()计算的索引从0变为数组-1的大小。当一个数字出来时,您将其从数组中取出:

NSMutableArray* availableNumbers=[NSMutableArray new];
for(NSUInteger i=0; i<10; i++)
{
    [availableNumbers addObject: @(i)];
}
for(NSUInteger i=0; i<10; i++)
{
    NSUInteger index= arc4random()%availableNumbers.count;
    NSNumber* number= availableNumbers[index];
    NSLog(@"%@",number);
    [availableNumbers removeObjectAtIndex: index];
}

PS:在最后一次迭代中起诉arc4random()是没用的,因为里面只有一个数字。