Search code examples
rubyprobabilitycoin-flipping

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


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?


Solution

  • 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.