代码之家  ›  专栏  ›  技术社区  ›  rustyshelf

在Objective-C中生成随机数

  •  725
  • rustyshelf  · 技术社区  · 18 年前

    我主要是一个Java高手,我想要一种生成0到74之间的伪随机数的方法。在Java中,我将使用以下方法:

    Random.nextInt(74)
    

    我对关于种子或真正的随机性的讨论不感兴趣,只对你如何在Objective-C中完成同样的任务感兴趣。我搜索了谷歌,那里似乎有很多不同和相互冲突的信息。

    13 回复  |  直到 11 年前
        1
  •  1035
  •   Paulo Mattos    7 年前

    你应该使用 arc4random_uniform() rand . 你甚至不需要播种。

    #include <stdlib.h>
    // ...
    // ...
    int r = arc4random_uniform(74);
    

    arc4random 手册页:

    NAME
         arc4random, arc4random_stir, arc4random_addrandom -- arc4 random number generator
    
    LIBRARY
         Standard C Library (libc, -lc)
    
    SYNOPSIS
         #include <stdlib.h>
    
         u_int32_t
         arc4random(void);
    
         void
         arc4random_stir(void);
    
         void
         arc4random_addrandom(unsigned char *dat, int datlen);
    
    DESCRIPTION
         The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8
         bit S-Boxes.  The S-Boxes can be in about (2**1700) states.  The arc4random() function returns pseudo-
         random numbers in the range of 0 to (2**32)-1, and therefore has twice the range of rand(3) and
         random(3).
    
         The arc4random_stir() function reads data from /dev/urandom and uses it to permute the S-Boxes via
         arc4random_addrandom().
    
         There is no need to call arc4random_stir() before using arc4random(), since arc4random() automatically
         initializes itself.
    
    EXAMPLES
         The following produces a drop-in replacement for the traditional rand() and random() functions using
         arc4random():
    
               #define foo4random() (arc4random() % ((unsigned)RAND_MAX + 1))
    
        2
  •  427
  •   Community Mohan Dere    9 年前

    arc4random_uniform(upper_bound) 函数生成一个范围内的随机数。以下内容将生成一个介于0和73之间(含0和73)的数字。

    arc4random_uniform(74)
    

    ARC4随机统一(上界) modulo bias 如手册页所述:

    arc4random_uniform()将返回小于上限的均匀分布随机数。arc4random_uniform()建议使用在类似“arc4random()%上限”的构造上,因为它避免了

        3
  •  64
  •   James Ko    10 年前

    和C一样,你会这样做

    #include <time.h>
    #include <stdlib.h>
    ...
    srand(time(NULL));
    int r = rand() % 74;
    

    编辑: 请随意替换 random() 或 arc4random() 对于 rand() (正如其他人所指出的那样,这相当糟糕)。

        4
  •  51
  •   Peter Mortensen Pieter Jan Bonestroo    11 年前

    - (NSInteger)randomValueBetween:(NSInteger)min and:(NSInteger)max {
        return (NSInteger)(min + arc4random_uniform(max - min + 1));
    }
    

    如果我在许多文件中使用它,我通常将宏声明为

    #define RAND_FROM_TO(min, max) (min + arc4random_uniform(max - min + 1))
    

    例如。

    NSInteger myInteger = RAND_FROM_TO(0, 74) // 0, 1, 2,..., 73, 74
    

    注意:仅适用于iOS 4.3/OSXv10.7(Lion)及更高版本

        5
  •  44
  •   Tibidabo    14 年前

    这会给你一个惊喜 介于0和47之间的数字

    float low_bound = 0;      
    float high_bound = 47;
    float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);
    

    float rndValue = (((float)arc4random()/0x100000000)*47);
    

    下限和上限都可以使用 消极的

    float low_bound = -35.76;      
    float high_bound = 12.09;
    float rndValue = (((float)arc4random()/0x100000000)*(high_bound-low_bound)+low_bound);
    

    将结果转换为圆角 整数 价值:

    int intRndValue = (int)(rndValue + 0.5);
    
        6
  •  37
  •   Michael Buckley    18 年前

    根据rand(3)的手册页,rand系列函数已被random(3)淘汰。这是因为rand()的低12位通过循环模式。要获得一个随机数,只需通过使用无符号种子调用srandom()对生成器进行种子设定,然后调用random()。因此,上述代码的等价物是

    #import <stdlib.h>
    #import <time.h>
    
    srandom(time(NULL));
    random() % 74;
    

        7
  •  31
  •   AW101    12 年前

    更好地使用 arc4random_uniform

    确定是否 arc4random_均匀

    #include <stdlib.h>
    
    int r = 0;
    if (arc4random_uniform != NULL)
        r = arc4random_uniform (74);
    else
        r = (arc4random() % 74);
    
        8
  •  14
  •   Eli    16 年前

    头文件:

    //Random.h
    void initRandomSeed(long firstSeed);
    float nextRandomFloat();
    

    //Random.m
    static unsigned long seed;
    
    void initRandomSeed(long firstSeed)
    { 
        seed = firstSeed;
    }
    
    float nextRandomFloat()
    {
        return (((seed= 1664525*seed + 1013904223)>>16) / (float)0x10000);
    }
    

    这是一种非常经典的生成伪随机数的方法。在我的应用程序中,我调用:

    #import "Random.h"
    
    - (void)applicationDidFinishLaunching:(UIApplication *)application
    {
        initRandomSeed( (long) [[NSDate date] timeIntervalSince1970] );
        //Do other initialization junk.
    }
    

    float myRandomNumber = nextRandomFloat() * 74;
    

    请注意,此方法返回一个介于0.0f(包含)和1.0f(排除)之间的随机数。

        9
  •  7
  •   Tom Howard vancexu    11 年前

    arc4random_uniform(75)

        10
  •  4
  •   jezrael    11 年前

    生成0到99之间的随机数:

    int x = arc4random()%100;
    

    int x = (arc4random()%501) + 500;
    
        11
  •  4
  •   TwoStraws    10 年前

    从iOS 9和OS X 10.11开始,您可以使用新的GameplayKit类以多种方式生成随机数。

    在最简单的级别上,您可以从系统的内置随机源生成一个随机数,如下所示:

    NSInteger rand = [[GKRandomSource sharedRandom] nextInt];
    

    这将生成一个介于-2147483648和2147483647之间的数字。如果您想要一个介于0和上限(独占)之间的数字,您可以使用:

    NSInteger rand6 = [[GKRandomSource sharedRandom] nextIntWithUpperBound:6];
    

    GameplayKit内置了一些方便的构造函数来处理骰子。例如,您可以像这样滚动六面模具:

    GKRandomDistribution *d6 = [GKRandomDistribution d6];
    [d6 nextInt];
    

    GKShuffledDistribution .

        12
  •  2
  •   soumya tehie    11 年前

    //下面的示例将生成一个介于0和73之间的数字。

    int value;
    value = (arc4random() % 74);
    NSLog(@"random number: %i ", value);
    
    //In order to generate 1 to 73, do the following:
    int value1;
    value1 = (arc4random() % 73) + 1;
    NSLog(@"random number step 2: %i ", value1);
    

    输出:

    • 随机数步骤2:

        13
  •  1
  •   Robert Wasmann    10 年前

    对于游戏开发人员,使用random()生成随机数。可能至少比使用arc4random()快5倍。模偏差不是一个问题,尤其是在游戏中,当使用全范围的随机数()生成随机数时。一定要先播种。在AppDelegate中调用srandomdev()。以下是一些帮助器函数:

    static inline int random_range(int low, int high){ return (random()%(high-low+1))+low;}
    static inline CGFloat frandom(){ return (CGFloat)random()/UINT32_C(0x7FFFFFFF);}
    static inline CGFloat frandom_range(CGFloat low, CGFloat high){ return (high-low)*frandom()+low;}