1

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.

max pleaner
  • 26,189
  • 9
  • 66
  • 118

2 Answers2

3
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
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
1
# prob : Probability (Float between 0 and 1)
def flip_weighted_coin(prob)
  (rand < prob) ? :heads : :tails
end
user1934428
  • 19,864
  • 7
  • 42
  • 87