Class: GeneticAlgorithms::RouletteWheel
- Inherits:
-
Object
- Object
- GeneticAlgorithms::RouletteWheel
- Defined in:
- lib/genetic_algorithms/roulette_wheel.rb
Instance Method Summary collapse
-
#initialize(chromosomes_and_scores) ⇒ RouletteWheel
constructor
A new instance of RouletteWheel.
-
#spin ⇒ Object
TODO: use inject here instead of each_pair.
Constructor Details
#initialize(chromosomes_and_scores) ⇒ RouletteWheel
Returns a new instance of RouletteWheel.
5 6 7 8 9 10 11 12 13 14 15 |
# File 'lib/genetic_algorithms/roulette_wheel.rb', line 5 def initialize chromosomes_and_scores chromosomes_and_scores = NaturalHash[ chromosomes_and_scores ] total = chromosomes_and_scores.values.inject(:+) @logger = Logging.logger[self] normalized = chromosomes_and_scores.map do |chromosome, score| [chromosome, score.to_f/total] end @normalized = normalized.sort_by { |chromosome, probability| probability } end |
Instance Method Details
#spin ⇒ Object
TODO: use inject here instead of each_pair
18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/genetic_algorithms/roulette_wheel.rb', line 18 def spin accumulator, prn = 0, rand @normalized.each_pair do |chromosome, probability| if prn <= probability + accumulator @logger.debug "Choosing #{chromosome} with probability #{probability}" return chromosome end accumulator += probability end end |