如何生成不重复的随机数

2023-12-07

我正在尝试随机化数组中的数字。我可以使用arc4random() % [indexes count]

我的问题是 - 如果一个数组由 20 个项目组成,则每次数组洗牌时,在 5 个批次中,应该出现不同的数字。例子 :

第一次洗牌:1,4,2,5,6。

第二次洗牌:7,12,9,15,3

-(IBAction)randomNumbers:(UIButton *)sender
{
    int length = 10; // int length = [yourArray count];

    NSMutableArray *indexes = [[NSMutableArray alloc] initWithCapacity:length];
    for (int i=0; i<5; i++)
        [indexes addObject:[NSNumber numberWithInt:i]];

    NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:length];

    while ([indexes count])
    {
        int index = arc4random() % [indexes count];
        [shuffle addObject:[indexes objectAtIndex:index]];
        [indexes removeObjectAtIndex:index];
    }

    //    for (int i=0; i<[shuffle count]; i++)
    NSLog(@"%@", [shuffle description]);
}

根据您的要求...请检查此代码

将此设为属性

@synthesize alreadyGeneratedNumbers;

将这些方法添加到您的 .m 中

-(int)generateRandomNumber{

    int TOTAL_NUMBER=20;

    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 *shuffle = [[NSMutableArray alloc] initWithCapacity:5];

    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];
        }
    }

    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];
    }


}

我仍然觉得你需要一些改变,比如

它会给你正确的值,但是如果用户按第五次怎么办?

在 20 个号码中,您已经选择了 4 组,每组 5 个号码,在第 6 次时,它将循环搜索下一组号码,并且将变为无限。

所以你可以做的是,保持随机播放的轨迹,一旦达到限制,即 20/5=4,禁用随机按钮。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何生成不重复的随机数 的相关文章

随机推荐