1

在这里,我使用以下代码对 NSMuttable 数组进行洗牌,而洗牌数组只重复一个值,其余的一切正常,我应该做哪些改变来洗牌而不重复?

words = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3",@"4", nil] ;
NSUInteger count = [words count];

for (int i = 0; i < count; i++)
   {
    NSInteger nElements = count - i;
    NSInteger n = (arc4random() % nElements) + i;
    NSLog(@"n val %d i val %d",i,n);
    [words exchangeObjectAtIndex:i withObjectAtIndex:n];
   }

NSlog 输出

2012-12-31 12:49:05.730 quizer[1607:c07] n val 0 i val 0
2012-12-31 12:49:05.731 quizer[1607:c07] n val 1 i val 3
2012-12-31 12:49:05.731 quizer[1607:c07] n val 2 i val 2
2012-12-31 12:49:05.732 quizer[1607:c07] n val 3 i val 3

请帮我解决

4

2 回答 2

1

这段代码可以帮助你,

shuffle 数组只包含 0 到 TOTAL_NUMBER(您的数组大小)之间的每个数字一次。

您可以从中洗牌现有的阵列。

@synthesize alreadyGeneratedNumbers;//this is a mutableArray.


int TOTAL_NUMBER=5;//size of array


-(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)randomNumbers:(UIButton *)sender
{

    NSMutableArray *startArray=[NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];

    NSMutableArray *shuffle = [NSMutableArray new];

    BOOL contains=YES;
    while ([shuffle count]<5) {
        NSNumber *generatedNumber=[NSNumber numberWithInt:[self generateRandomNumber]];
        //NSLog(@"->%@",generatedNumber);

        if (![alreadyGeneratedNumbers containsObject:generatedNumber]) {
            [shuffle addObject:generatedNumber];
            contains=NO;
            [alreadyGeneratedNumbers addObject:generatedNumber];
        }
    }
    if ([alreadyGeneratedNumbers count] >= TOTAL_NUMBER) {
        NSLog(@"\nOne shuffel ended.....what to reshuffle");
        [alreadyGeneratedNumbers removeAllObjects];
    }

    NSMutableArray *shuffledArray=[NSMutableArray new];
    for (NSNumber *index in shuffle) {
        [shuffledArray addObject:[startArray objectAtIndex:[index integerValue]]];
    }
    NSLog(@"Shuffled array = %@",shuffledArray);
}
于 2012-12-31T07:53:31.913 回答
0

要从您的 中删除重复项NSMutableArray

// Removing duplicate entry from array
NSArray *copy = [words copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator])
{
    if ([words indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound)
    {
        [words removeObjectAtIndex:index];
    }
    index--;
}
[copy release];

您可以在每次添加对象时检查它。

于 2012-12-31T07:26:35.683 回答