Class: GeneGenie::Gene
- Inherits:
-
Object
- Object
- GeneGenie::Gene
- Defined in:
- lib/gene_genie/gene.rb
Overview
A Gene is the basic unit of the genetic algorithm. Genes hold the information used to evaluate their fitness. They are combined into new Genes during the optimisation process.
Instance Method Summary collapse
- #<=>(other) ⇒ Object
- #combine(other_gene) ⇒ Object
- #fitness ⇒ Object
-
#initialize(information, fitness_evaluator) ⇒ Gene
constructor
A new instance of Gene.
- #mutate(mutator) ⇒ Object
- #to_hashes ⇒ Object
Constructor Details
#initialize(information, fitness_evaluator) ⇒ Gene
Returns a new instance of Gene.
7 8 9 10 11 12 13 |
# File 'lib/gene_genie/gene.rb', line 7 def initialize(information, fitness_evaluator) fail ArgumentError, 'information must be Array' unless information.kind_of? Array fail ArgumentError, 'information must be Array of Hashes' unless information[0].kind_of? Hash @information = information @fitness_evaluator = fitness_evaluator end |
Instance Method Details
#<=>(other) ⇒ Object
41 42 43 |
# File 'lib/gene_genie/gene.rb', line 41 def <=>(other) fitness <=> other.fitness end |
#combine(other_gene) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/gene_genie/gene.rb', line 29 def combine(other_gene) other_gene_hash = other_gene.to_hashes new_information = @information.map.with_index do |part, index| new_hash = {} part.each do |k, v| new_hash[k] = (rand > 0.5) ? v : other_gene_hash[index][k] end new_hash end Gene.new(new_information, @fitness_evaluator) end |
#fitness ⇒ Object
19 20 21 |
# File 'lib/gene_genie/gene.rb', line 19 def fitness @fitness ||= @fitness_evaluator.fitness(@information) end |
#mutate(mutator) ⇒ Object
23 24 25 26 27 |
# File 'lib/gene_genie/gene.rb', line 23 def mutate(mutator) @information = mutator.call @information @fitness = nil self end |
#to_hashes ⇒ Object
15 16 17 |
# File 'lib/gene_genie/gene.rb', line 15 def to_hashes @information end |