Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate random numbers on iOS?

Tags:

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.

like image 777
user21293 Avatar asked Feb 04 '09 07:02

user21293


People also ask

Is there a random number generator app?

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.

How do I generate random numbers in Xcode?

To generate a random number in Swift, use Int. random() function. Int. random() returns a number, that is randomly selected, in the given range.


2 Answers

There is a very similar question here on StackOverFlow. Here is one of the better solutions (no need for seeding):

int r = arc4random() % 5; 
like image 115
newtonapple Avatar answered Sep 30 '22 06:09

newtonapple


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

like image 34
Andy Jacobs Avatar answered Sep 30 '22 06:09

Andy Jacobs