如何生成非重复随机数 [英] How to generate non repeating random number

查看:157
本文介绍了如何生成非重复随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在数组中随机化数字。我可以这样做使用 arc4random()%[索引计数]

I am trying to randomize numbers in an array. I am able to do that using arc4random() % [indexes count]

我的问题是 - 由20个项目组成,每次数组shuffle,在一批5中,不同的数字应该出现。示例:

My problem is - If an array consists of 20 items, every time the array shuffles, in a batch of 5, different number should appear. Example :

第一个shuffle:1,4,2,5,6。

first shuffle: 1,4,2,5,6.

12,9,15,3

second shuffle: 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中添加这些方法

Add these methods in your .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];
    }


}

你需要一些变化,例如

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

it will give you correct value, but what if user pressed 5th time?

您已经选择了20个数字中的4个5个数字,第6次,它将循环搜索下一组数字,并将变为无限。

out of 20 numbers you already picked 4 sets of 5 number, on on 6th time it will be in loop to search for next set of numbers and will become infinite.

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

So what you can do is, keep the track of shuffle and once it reaches the limit i.e, 20/5=4 disable the random button.

这篇关于如何生成非重复随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆