0

Is there a method in objective-c that allows you to pseudorandomly decide between two ints? Or is there a quick way to implement this?

locoboy
  • 38,002
  • 70
  • 184
  • 260
  • 1
    For a detailed discussion on Random numbers in objective-c (including why you shouldn't use rand!) see http://stackoverflow.com/questions/160890/generating-random-numbers-in-objective-c. – RB. Apr 21 '11 at 08:55

3 Answers3

4

Use the following:

int number = arc4random() % 2;
if(number==0){
  //pick one number
}else{
  //pick other number
}
Tovi7
  • 2,793
  • 3
  • 23
  • 27
  • A slight better looking is to use ternary operator. +1 though. – taskinoor Apr 21 '11 at 09:08
  • That is a uselessly heavy calculation. Why arc4? No simple random that returns float in between 0 and 0,(9) in ObjC? –  Apr 25 '11 at 11:38
2
randomSelection = arc4random() % 2 ? choice1 : choice2;
taskinoor
  • 45,586
  • 12
  • 116
  • 142
0

in C++ that would be result = rand() < 0.5 ? int1 : int2 why can't you build the same command in ObjC?