iphone中不重复的随机数? [英] Non repeating random numbers in iphone?

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

问题描述


可能重复:

非重复随机数

任何人都可以告诉我如何生成非重复的随机数?

Can any one tell me how to generate non repeating random numbers?

我在很多网站上都看过这个,但是他们提供了main.c文件代码。

I saw this on many sites but they give in main.c file code.

当我使用main.c文件时,代码工作正常,但是当我尝试转换为my.m文件时,它无效。

When I use the main.c file the code working is fine, but when I try to convert in to my.m file it is not working.

示例:

我需要随机获得0-10之间的所有数字。这些数字不应再重复。

i need to get all the numbers between 0-10 randomly.and the numbers should not repeat again.

在此先感谢。

推荐答案

    NSMutableArray *storeArray = [[NSMutableArray alloc] init];    
    BOOL record = NO;
    int x;

    for (int i=0; [storeArray count] < 10; i++) //Loop for generate different random values
    {
        x = arc4random() % 10;//generating random number
        if(i==0)//for first time 
        {
          [storeArray addObject:[NSNumber numberWithInt:x]];  
        }
        else
        {
            for (int j=0; j<= [storeArray count]-1; j++) 
            {
                    if (x ==[[storeArray objectAtIndex:j] intValue]) 
                    record = YES;
            }

            if (record == YES) 
            {
                record = NO;
            }
            else
            {
                [storeArray addObject:[NSNumber numberWithInt:x]];
            }
        }
    }
    NSLog(@" Non Repeated Random Numbers : %@",storeArray);

你可以试试这段代码可能会对你充分使用

can u try this code may be it's use full to you

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

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