开发者社区> 问答> 正文

随机分配数组重复值

爵霸 2016-03-26 10:02:39 774

代码实现随机分配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)
  • 爵霸
    2019-07-17 19:15:28

    随机分配数组包括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);
    }
    0 0
+ 订阅

时时分享云计算技术内容,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。

推荐文章