Mershual
Mershual

Reputation: 27

iOS arc4random NOT beginning from 0

i used arc4random to create a random number, is there a way to tell arc4random to begin at for example -5 instead of 0? because i want to create a random number in the range of -3,4 to 4,3, im not that good in iOS developing yet, so what other possiblities do i have if that wont work with arc4random (Links are appreciated if theres a guide or something like that)

Upvotes: 0

Views: 2343

Answers (3)

Femaref
Femaref

Reputation: 61437

First of all, use arc4random_uniform to get a random number in the desired absolute range (for -3 to 4 it would be 7): arc4random_uniform(7).

You might also see the form arc4random() % max, but that will introduce a modulo bias making the distribution less random, arc4random_uniform is prefered.

Afterwards, adjust your lower bound:

arc4random_uniform(7) - 3

apple docs

Upvotes: 7

David Schwartz
David Schwartz

Reputation: 182763

If you want it to start at -5 instead of 0, just subtract 5.

If you want to create a random number in the range of -3 to 4, just create a number from 0 to 7 and subtract 3 from it.

The arc4random function gives you a number from zero to 4,294,967,295. To change that to a number from 0 to 7, just divide by 613,566,756. (Or use arc4random_uniform to avoid any bias.)

Upvotes: 0

tiwo
tiwo

Reputation: 3349

Since arc4random() % n returns an integer from 0..n-1, arc4random() % (n - k) + k returns one from k..n-1. Plug in k=-5. Is that what you need?

Upvotes: 0

Related Questions