Kyle Decot
Kyle Decot

Reputation: 20815

How to randomly choose true/false w/ weight in Ruby

I have created a function below that randomly chooses true or false w/ the chances of each being 50% by default. This function is by no means perfect. How would you refactor this method to make it more concise?

def choose(weight = 50)
  bucket = []
  weight.times do
    bucket << true
  end
  while bucket.size < 100
    bucket << false
  end
  bucket.sample
end

Upvotes: 1

Views: 1562

Answers (3)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230471

If you need only these values (true/false), it's a little bit easier than picking arbitrary values.

def choose(weight = 50)
  chance = rand() # value between 0 and 1
  chance <= weight / 100.0
end

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

Upvotes: 3

UncleGene
UncleGene

Reputation: 2142

Simple equivalent of your function (100 discrete buckets)

def choose(weight = 50) 
  rand(100) < weight
end

Upvotes: 3

Thiago Lewin
Thiago Lewin

Reputation: 2828

The following implementation is more concise, fast and ruby-like:

def choose(weight = 50)
  rand <= weight/100.0
end

Upvotes: 11

Related Questions