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)
I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C. I've scoured Google, and there just seems to be lots of different and conflicting bits of information.
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(upper_bound)
avoids modulo bias as described in the man page: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:
Implementation file:
It's a pretty classic way of generating pseudo-randoms. In my app delegate I call:
Then later I just say:
Note that this method returns a random number between 0.0f (inclusive) and 1.0f (exclusive).
There are some great, articulate answers already, but the question asks for a random number between 0 and 74. Use:
arc4random_uniform(75)
For game dev use random() to generate randoms. Probably at least 5x faster than using arc4random(). Modulo bias is not an issue, especially for games, when generating randoms using the full range of random(). Be sure to seed first. Call srandomdev() in AppDelegate. Here's some helper functions:
Same as C, you would do
(assuming you meant including 0 but excluding 74, which is what your Java example does)
Edit: Feel free to substitute
random()
orarc4random()
forrand()
(which is, as others have pointed out, quite sucky).This will give you a floating point number between 0 and 47
Or just simply
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
Convert result to a rounder Integer value: