Albert Renshaw
Albert Renshaw

Reputation: 17902

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);

Upvotes: 5

Views: 459

Answers (2)

Lluís
Lluís

Reputation: 588

short int randomNumber () {
return arc4random() % 2 ? 1 : -1;
}

Upvotes: 1

Sebastian
Sebastian

Reputation: 7720

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

or arc4random_uniform(2)*2 - 1

Upvotes: 12

Related Questions