Generating random numbers in Objective-C

前端 未结 13 2244
孤街浪徒
孤街浪徒 2020-11-22 02:07

I\'m a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:

Random.nextInt(74)


        
相关标签:
13条回答
  • 2020-11-22 02:33

    I wrote my own random number utility class just so that I would have something that functioned a bit more like Math.random() in Java. It has just two functions, and it's all made in C.

    Header file:

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

    Implementation file:

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

    It's a pretty classic way of generating pseudo-randoms. In my app delegate I call:

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

    Then later I just say:

    float myRandomNumber = nextRandomFloat() * 74;
    

    Note that this method returns a random number between 0.0f (inclusive) and 1.0f (exclusive).

    0 讨论(0)
  • 2020-11-22 02:36

    This will give you a floating point number between 0 and 47

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

    Or just simply

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

    Both lower and upper bound can be negative as well. The example code below gives you a random number between -35.76 and +12.09

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

    Convert result to a rounder Integer value:

    int intRndValue = (int)(rndValue + 0.5);
    
    0 讨论(0)
  • 2020-11-22 02:36

    Better to use arc4random_uniform. However, this isn't available below iOS 4.3. Luckily iOS will bind this symbol at runtime, not at compile time (so don't use the #if preprocessor directive to check if it's available).

    The best way to determine if arc4random_uniform is available is to do something like this:

    #include <stdlib.h>
    
    int r = 0;
    if (arc4random_uniform != NULL)
        r = arc4random_uniform (74);
    else
        r = (arc4random() % 74);
    
    0 讨论(0)
  • 2020-11-22 02:37

    You should use the arc4random_uniform() function. It uses a superior algorithm to rand. You don't even need to set a seed.

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

    The arc4random man page:

    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))
    
    0 讨论(0)
  • 2020-11-22 02:37

    Use the arc4random_uniform(upper_bound) function to generate a random number within a range. The following will generate a number between 0 and 73 inclusive.

    arc4random_uniform(74)
    

    arc4random_uniform(upper_bound) avoids modulo bias as described in the man page:

    arc4random_uniform() will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.

    0 讨论(0)
  • 2020-11-22 02:42

    //The following example is going to generate a number between 0 and 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);
    

    Output:

    • random number: 72

    • random number step 2: 52

    0 讨论(0)
提交回复
热议问题