Skip to content

Instantly share code, notes, and snippets.

@henrik
Created August 6, 2012 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henrik/3276573 to your computer and use it in GitHub Desktop.
Save henrik/3276573 to your computer and use it in GitHub Desktop.
# 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
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