def weighted_random(rules) total = rules.values.reduce(&:+) srand chance = rand(0..total) rules.each do |item, weight| return item unless chance > weight chance -= weight end end symbols = %i(bird fish turtle) # ruby 2.0 weights = [0.5, 0.4, 0.1] # for convenience sum = 1.0 rules = symbols.zip(weights).to_h # ruby 2.0 count_bird = 0 count_fish = 0 count_turtle = 0 10_000.times do case weighted_random(rules) when :bird count_bird += 1.0 when :fish count_fish += 1.0 when :turtle count_turtle += 1.0 end end puts format('bird %0.4f', count_bird / 10_000) puts format('fish %0.4f', count_fish / 10_000) puts format('turtle %0.4f', count_turtle / 10_000)
Result
bird 0.5001 fish 0.3976 turtle 0.1023
No comments:
Post a Comment