Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating unique random number in objective c?

I want to generate a random number between 31 to 60.

So i have used rand() but i think it will give some time same value.But i need ebvery time it should give me new value.

How can i do this?

like image 278
user930195 Avatar asked Mar 02 '26 09:03

user930195


2 Answers

Use arc4random(), it will provide a good random number and does not require seeding.

rand() will produce the same sequence each time the app is run unless you seed it with a unique value.

Then it is a matter or reducing the range. A simple solution is to mod to the range and add the low end of the range. (This will cause a small bias that should be acceptable.)

Example:

int rangeLow = 31;
int rangeHigh = 60;
int randomNumber = arc4random() % (rangeHigh-rangeLow+1) + rangeLow;

If what you want each number in the range to occur only once then @pawan.mangal has a link to a good solution.

like image 101
zaph Avatar answered Mar 04 '26 21:03

zaph


Instead of rand() you can use arc4random()

To get an integer value from arc4random() that goes from 0 to x-1, you would do this:

int value = arc4random() % x;

To get an integer in the range 1 to x, just add 1:

int value = (arc4random() % x) + 1;

Finally, if you need to generate a floating point number, define this in your project:

#define ARC4RANDOM_MAX      0x100000000'

Then, you can use arc4random() to get a floating point value (at double the precision of using rand()), between 0 and 100, like so:

double val = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f);
like image 42
bilash.saha Avatar answered Mar 04 '26 21:03

bilash.saha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!