1

Possible Duplicate:
Generating non-repeating random numbers

Here is my code

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

this output should be like 8 7 9 2 1 4 6 3 5 0 Which is random and not repeating numbers

4

3 回答 3

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];
}
于 2012-12-14T13:27:53.960 回答
0

这个答案是我在 SO 中的一个答案的修改版本。

因此,您可能会在这里发现一些奇怪的东西,但是您可以使用它,因为您的要求相似。

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];
    }
}
于 2012-12-14T13:54:20.073 回答
-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() 是没有用的,因为里面只有一个数字。

于 2012-12-14T13:57:29.007 回答