public
Created

  • Download Gist
claudiu.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 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
claudiu_objectified.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.