max pleaner max pleaner - 2 months ago 12
Ruby Question

coin flipper with N probability of heads

The goal is to flip a weighted coin such that it returns heads N percent of the time.

I'm not totally stumped here. I can do it this way:

probability = 0.75 # chance of getting heads as decimal
num_heads_cases = (100.to_f * probability).to_i
cases = num_heads_cases.times.map { :heads }.concat(
(100 - num_heads_cases).times.map { :tails }
)
is_flip_result_heads = cases.sample == :heads


But I'm posting here to see if there's not some core ruby / rails method I'm overlooking. I'm looking for something similar to the following method signature:

def random_bool(probability_of_returning_true=0.5)


This is similar to the question it's marked as a duplicate of but is not a duplicate; that question asks how to get a random number, while this one asks how to get a random boolean with probability.

It might seem obvious how to go from "random number" to "random boolean" but it's evidently not that way to everyone.

Answer
def rb(prob=0.5)
  rand < prob
end

10.times.map { rb(0.8) }
  #=> [true, true, false, false, true, false, true, true, true, true]

100.times.reduce(0) { |t,_| t + (rb(0.8) ? 1 : 0) }/100.0
  #=> 0.87

1000.times.reduce(0) { |t,_| t + (rb(0.8) ? 1 : 0) }/1000.0
  #=> 0.798 

10000.times.reduce(0) { |t,_| t + (rb(0.8) ? 1 : 0) }/10000.0
  #=> 0.8003