Class: GeneGenie::Gene

Inherits:
Object
  • Object
show all
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.

Since:

  • 0.0.1

Instance Method Summary collapse

Constructor Details

#initialize(information, fitness_evaluator) ⇒ Gene

Returns a new instance of Gene.

Since:

  • 0.0.1



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

Since:

  • 0.0.1



41
42
43
# File 'lib/gene_genie/gene.rb', line 41

def <=>(other)
  fitness <=> other.fitness
end

#combine(other_gene) ⇒ Object

Since:

  • 0.0.1



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

#fitnessObject

Since:

  • 0.0.1



19
20
21
# File 'lib/gene_genie/gene.rb', line 19

def fitness
  @fitness ||= @fitness_evaluator.fitness(@information)
end

#mutate(mutator) ⇒ Object

Since:

  • 0.0.1



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_hashesObject

Since:

  • 0.0.1



15
16
17
# File 'lib/gene_genie/gene.rb', line 15

def to_hashes
  @information
end