-3

I am wondering if I can use the rand() function to randomly choose between 2 variables. Say I have thing1 and thing2, can rand() choose one of them for me?

My current code just used rand() to generate a random number and I say if its odd then thing1 and if even then thing2 but if I add thing3 then it wont work..

IlyaS
  • 1
  • 1
  • 1
    The way you did it is exactly the way how to do it. – ckruczek Aug 15 '16 at 10:53
  • Did you succeed in choosing between 2 variables or not? – Awais Chishti Aug 15 '16 at 10:57
  • If the variables are all the same type, then it would be better to use an array than N distinct variables; you'd map the result of `rand()` to `[0..N-1]` (using the method described in the accepted answer of the linked question), where `N` is the number of elements in your array. – John Bode Aug 15 '16 at 14:00

2 Answers2

1

The rand function returns a number between 0 and RAND_MAX. inclusive.

Divide this range into X sub-ranges, where X is the number of "variables" you have. If the returned value is inside the first sub-range use the first "variable". If the returned value is inside the second sub-range then select the second variable. Etc.


You can also use the modulo operator to get a value in the range from 0 to X, where X again is the number of "variables" you have. Then use this single number to select the "variable" (for example by using it as an index into an array).

This method using modulo is not perfect. See e.g. this old answer for why and for a better way.

Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Suppose you have n things. First, generate a random number in a range of 0 to (k*n)-1, where k is a positive integer. Then, divide the generated number by k. You will get a number from 0 to n-1. Map 0 to thing1, 1 to thing2, and so on till you map n-1 to thing n.

Or even simpler, just generate a random number from 0 to n-1 and do the mapping as above.

GoodDeeds
  • 7,956
  • 5
  • 34
  • 61