Xcode arc4random() not behaving as expected

356 Views Asked by At

I have the following inputs (verified by NSLog): xleft = 128, xRight = 192. The next line of code uses these-

xPos = (arc4random() % xRight-xleft) + xleft;

On the last run, xPos = 53. By my calculations, it should be no less than 128 if the random number produced is zero (192 - 128 = 64, rand(64) = 0, 0 + 128 = 128. I am trying to generate random numbers in the range xLeft to xRight.

2

There are 2 best solutions below

1
On BEST ANSWER

Try:

xPos = (arc4random() % (xRight-xleft)) + xleft; 

Basically you're modding by xRIght and then subtracting xleft, instead of first subtracting xleft from xright and modding with the result.

Reference link: http://www.techotopia.com/index.php/Objective-C_2.0_Operator_Precedence

1
On

% has higher precedence in C and directly derived languages like Objective-C than + and -. It's equal to * and /.

So that expression is evaluated as:

  1. Get arc4random
  2. Get the modulus of that and xRight
  3. Subtract xLeft
  4. Add xLeft

So you should expect anything in the range [0, xRight)