Created
August 6, 2012 16:59
-
-
Save henrik/3276573 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://stackoverflow.com/a/11832301/6962 | |
# Translated from Python by Claudiu. | |
$tokens_in_slots = [0, 0, 0] | |
$slot_distributions = [0.5, 0.3, 0.2] | |
def pick_slot | |
sum_tokens = $tokens_in_slots.inject(:+) | |
if sum_tokens.zero? | |
slot = rand($tokens_in_slots.length) | |
else | |
expected_tokens = $slot_distributions.map { |d| d * sum_tokens } | |
errors = expected_tokens.zip($tokens_in_slots).map { |e, a| e - a } | |
slot = errors.index(errors.max) | |
end | |
$tokens_in_slots[slot] += 1 | |
end | |
100.times do | |
pick_slot | |
puts format("%s: %s", $tokens_in_slots.inject(:+), $tokens_in_slots) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Picker | |
def initialize(distributions) | |
@distributions = distributions | |
@tokens_in_slots = Array.new(@distributions.length, 0) | |
end | |
def pick_slot | |
@tokens_in_slots[next_slot] += 1 | |
end | |
def tokens_in_slots | |
@tokens_in_slots | |
end | |
def total_tokens | |
@tokens_in_slots.inject(:+) | |
end | |
private | |
def next_slot | |
sum_tokens = @tokens_in_slots.inject(:+) | |
if sum_tokens.zero? | |
rand(@tokens_in_slots.length) | |
else | |
expected_tokens = @distributions.map { |d| d * sum_tokens } | |
errors = expected_tokens.zip(@tokens_in_slots).map { |e, a| e - a } | |
errors.index(errors.max) | |
end | |
end | |
end | |
picker = Picker.new([0.5, 0.3, 0.2]) | |
100.times do | |
picker.pick_slot | |
puts format("%s: %s", picker.total_tokens, picker.tokens_in_slots) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment