Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Ruby中随机选择真/假w/权重_Ruby - Fatal编程技术网

如何在Ruby中随机选择真/假w/权重

如何在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

我在下面创建了一个函数,可以随机选择true或false,默认情况下每个值的概率为50%。这一功能绝非完美。您将如何重构此方法以使其更简洁

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