max pleaner - 1 year ago 108

Ruby Question

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

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

```
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
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**