What is the best way to generate random numbers using Objective-C on iOS?
If I use (int)((double) rand() / ((double)(RAND_MAX) + (double) 1) * 5.0)
to generate a number from 0 to 4, every time I start the program on the iPhone it generates the same numbers to start off with.
RNG – Random Number Generator Whether you need a random number quickly, this app is such a life saver. Choose numbers randomly out of a list for any purposes, such as dice game or quizzes. It also works excellently to help you make random decisions.
To generate a random number in Swift, use Int. random() function. Int. random() returns a number, that is randomly selected, in the given range.
There is a very similar question here on StackOverFlow. Here is one of the better solutions (no need for seeding):
int r = arc4random() % 5;
i use
#define RANDOM_SEED() srandom(time(NULL)) #define RANDOM_INT(__MIN__, __MAX__) ((__MIN__) + random() % ((__MAX__+1) - (__MIN__)))
so you can give a min and max
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With