Ruby 根据结果预测中奖人数?

Ruby 根据结果预测中奖人数?,ruby,Ruby,我想根据CSV上的最新彩票结果生成最可能的数字 我有这个剧本: h = Hash.new f = File.open('numbers.csv', "r") f.each_line { |line| numbers = line.split numbers.each { |w| if h.has_key?(w) h[w] = h[w] + 1 else h[w] = 1 end } } # sorteamos el hash por

我想根据CSV上的最新彩票结果生成最可能的数字

我有这个剧本:

h = Hash.new
f = File.open('numbers.csv', "r")
f.each_line { |line|
  numbers = line.split
  numbers.each { |w|
    if h.has_key?(w)
      h[w] = h[w] + 1
    else
      h[w] = 1
    end
  }
}

# sorteamos el hash por valor, y lo pintamos según la concurrencia
h.sort{|a,b| a[1]<=>b[1]}.each { |elem|
  puts "\"#{elem[0]}\" tiene #{elem[1]} concurrencia"
}
这将告诉我哪些数字最容易出错。 我想根据这些结果抽取一个概率最大的数字


我怎样才能做到这一点?谢谢

我认为Ruby没有一种内置的优雅方式来实现这一点。您可以将散列视为一组存储箱,其中每个数字的出现次数就是存储箱的大小。然后,您可以计算总的箱子宽度,获得一个随机样本,然后迭代以找出样本落在哪个箱子中

def weighted_sample h
  weight = h.values.reduce(:+)
  sample = rand weight
  h.each do |n, w|
    return n if sample < w
    sample -= w
  end
end

Array.new(10) { weighted_sample({1 => 8, 2 => 4, 3 => 2}) }
# [2, 2, 1, 1, 1, 3, 1, 1, 1, 1]

您的意思是希望从哈希表中选择命中率最高的项目吗?或者您想从散列中随机选取一个项目,通过散列值进行加权?
h = Hash.new 0
# ...
h[w] += 1