Skip to content
This repository has been archived by the owner on Jun 1, 2021. It is now read-only.

Commit

Permalink
Fix bug in Ruby implementation of WeightedChoice
Browse files Browse the repository at this point in the history
Previous version of Ruby implementation of WeightedChoice did not work
correctly. New version has been verified to work correctly and has an
appropriate unit test.
  • Loading branch information
eytan committed Feb 16, 2015
1 parent c6a2e11 commit d361582
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 12 deletions.
13 changes: 7 additions & 6 deletions alpha/ruby/lib/plan_out/op_random.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,18 +57,19 @@ def simple_execute

return [] if choices.length() == 0

cum_weights = choices.zip(weights)
cum_weights = Array.new(weights.length)
cum_sum = 0.0

cum_weights.each do |choice, weight|
weights.each_with_index do |weight, index|
cum_sum += weight
cum_weights[choice] = cum_sum
cum_weights[index] = cum_sum
end

stop_value = get_uniform(0.0, cum_sum)

cum_weights.each do |choice, cum_weight|
choice if stop_value <= cum_weight
i = 0
cum_weights.each_with_index do |cum_weight, index|
return choices[index] if stop_value <= cum_weight
end
end
end
Expand All @@ -81,4 +82,4 @@ def simple_execute
choices[rand_index]
end
end
end
end
22 changes: 16 additions & 6 deletions alpha/ruby/test/plan_out/operator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,24 @@
module PlanOut
class OperatorTest < Minitest::Test
def setup
@operator = Operator.new({ foo: 'bar' })
@op_simple = OpSimple.new({ bar: 'qux' })
@a = Assignment.new('mtsalt')
end

def test_execute
a = Assignment.new('mtsalt')
assert_equal('mtsalt', @operator.execute(a))
assert_equal(-1, @op_simple.execute(a))
operator = Operator.new({ foo: 'bar' })
op_simple = OpSimple.new({ bar: 'qux' })
assert_equal('mtsalt', operator.execute(@a))
assert_equal(-1, op_simple.execute(@a))
end

def test_weighted_choice
weighted = WeightedChoice.new({
choices: ["c1", "c2", "c1"],
weights: [20, 40, 60],
unit: 42,
salt:'x'
})
assert_equal("c2", weighted.execute(@a))
end
end
end
end

0 comments on commit d361582

Please sign in to comment.