How to program an unfair or biased coin flip in Ruby?

1.5k Views Asked by At

I need to make a coin flip that obeys a certain probability of outcome. For example, a coin flip with a 67% chance of coming out Heads, 83% chance of coming out Tails, etc.

I managed to get the result I'm after by populating an array with 100 true and false in the equivalent distribution, then picking one item at random. What is a more elegant way to go about it?

2

There are 2 best solutions below

0
On BEST ANSWER

Random#rand(max) (and Kernel#rand(max)):

When max is an Integer [greater than or equal to 1], rand returns a random integer greater than or equal to zero and less than max..

So:

p = rand(100)
return p < 83  # ie. true for heads

In theory such can be "exact" like an array distribution method.

4
On
rand < 0.67
rand < 0.83

will give true with probability of 67% and 83%, respectively - because a uniformly selected random number x that is 0 <= x < 1 (such as returned by Kernel#rand) will be 67% likely to land in the segment 0 <= x < 0.67.