Search code examples
iosobjective-crandomintegersign

Randomly generate "-1" or "1" - Shortest Method


I need to randomly generate either a "-1" or a "1" to determine the sign of a number randomly... What's the shortest method? I am currently using this but it seems pretty long:

sign = (round((arc4random() % 2)))-((round((arc4random() % 2))) == 0);


Solution

  • What about arc4random_uniform(2) ? -1 : 1?

    or arc4random_uniform(2)*2 - 1