Class: Calyx::Production::WeightedChoices
- Inherits:
-
Object
- Object
- Calyx::Production::WeightedChoices
- Defined in:
- lib/calyx/production/weighted_choices.rb
Class Method Summary collapse
Instance Method Summary collapse
- #evaluate ⇒ Object
-
#initialize(collection) ⇒ WeightedChoices
constructor
A new instance of WeightedChoices.
Constructor Details
#initialize(collection) ⇒ WeightedChoices
Returns a new instance of WeightedChoices.
22 23 24 |
# File 'lib/calyx/production/weighted_choices.rb', line 22 def initialize(collection) @collection = collection end |
Class Method Details
.parse(productions, registry) ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/calyx/production/weighted_choices.rb', line 4 def self.parse(productions, registry) weights_sum = productions.reduce(0) do |memo, choice| memo += choice.last end raise 'Weights must sum to 1' if weights_sum != 1.0 choices = productions.map do |choice, weight| if choice.is_a?(String) [Concat.parse(choice, registry), weight] elsif choice.is_a?(Symbol) [NonTerminal.new(choice, registry), weight] end end self.new(choices) end |
Instance Method Details
#evaluate ⇒ Object
26 27 28 29 30 31 32 |
# File 'lib/calyx/production/weighted_choices.rb', line 26 def evaluate choice = @collection.max_by do |_, weight| rand ** (1.0 / weight) end.first [:weighted_choice, choice.evaluate] end |