如何在Ruby中随机选择真/假w/权重
我在下面创建了一个函数,可以随机选择true或false,默认情况下每个值的概率为50%。这一功能绝非完美。您将如何重构此方法以使其更简洁如何在Ruby中随机选择真/假w/权重,ruby,Ruby,我在下面创建了一个函数,可以随机选择true或false,默认情况下每个值的概率为50%。这一功能绝非完美。您将如何重构此方法以使其更简洁 def choose(weight = 50) bucket = [] weight.times do bucket << true end while bucket.size < 100 bucket << false end bucket.sample end 如果您只需要这些值tr
def choose(weight = 50)
bucket = []
weight.times do
bucket << true
end
while bucket.size < 100
bucket << false
end
bucket.sample
end
如果您只需要这些值true/false,那么选择任意值就容易一点
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]
如果您只需要这些值true/false,那么选择任意值就容易一点
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]
以下实现更加简洁、快速且类似ruby:
def choose(weight = 50)
rand <= weight/100.0
end
以下实现更加简洁、快速且类似ruby:
def choose(weight = 50)
rand <= weight/100.0
end
函数100离散桶的简单等价物
def choose(weight = 50)
rand(100) < weight
end
函数100离散桶的简单等价物
def choose(weight = 50)
rand(100) < weight
end