2 lpploverou LPPloveROU 于 2013.01.06 16:22 提问

随机分配数组重复值

代码实现随机分配NSMuttable Array,但是随机分配之后数组一直重复同一个值,我怎么修改能让他不再重复了?在ios6中。

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

1个回答

gaoXxxing
gaoXxxing   2013.01.06 17:15

随机分配数组包括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);
}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!