Generating random numbers in Objective-C

前端 未结 13 2452
孤街浪徒
孤街浪徒 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:23

    As of iOS 9 and OS X 10.11, you can use the new GameplayKit classes to generate random numbers in a variety of ways.

    You have four source types to choose from: a general random source (unnamed, down to the system to choose what it does), linear congruential, ARC4 and Mersenne Twister. These can generate random ints, floats and bools.

    At the simplest level, you can generate a random number from the system's built-in random source like this:

    NSInteger rand = [[GKRandomSource sharedRandom] nextInt];
    

    That generates a number between -2,147,483,648 and 2,147,483,647. If you want a number between 0 and an upper bound (exclusive) you'd use this:

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

    GameplayKit has some convenience constructors built in to work with dice. For example, you can roll a six-sided die like this:

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

    Plus you can shape the random distribution by using things like GKShuffledDistribution.

提交回复
热议问题