Class: Algorithms::GeneticAlgorithm::ArraySolution

Inherits:
Object
  • Object
show all
Includes:
Solution
Defined in:
lib/algorithms/genetic_algorithm/solutions/array.rb

Instance Attribute Summary

Attributes included from Solution

#data

Instance Method Summary collapse

Methods included from Solution

#create_new_solution, #valid?

Constructor Details

#initialize(array, possible_elements: [], mutate_change_rate: 0.5) ⇒ ArraySolution

Returns a new instance of ArraySolution.



4
5
6
# File 'lib/algorithms/genetic_algorithm/solutions/array.rb', line 4

def initialize(array, possible_elements: [], mutate_change_rate: 0.5)
  @data, @possible_elements, @mutate_change_rate = array, possible_elements, mutate_change_rate
end

Instance Method Details

#crossover(other_solution) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/algorithms/genetic_algorithm/solutions/array.rb', line 19

def crossover(other_solution)
  other_data = other_solution.data
  indices = rand(@data.size / 10).times.map { rand(@data.size) }.sort.<<(@data.size).each
  current_data = @data
  new_data = @data.map.with_index do |_element, idx|
    if idx == indices.peek
      current_data = current_data == @data ? other_data : @data
    end
    current_data[idx]
  end
  create_new_solution(new_data)
end

#mutateObject



8
9
10
11
12
13
14
15
16
17
# File 'lib/algorithms/genetic_algorithm/solutions/array.rb', line 8

def mutate
  new_data = @data.map do |val|
    if rand < @mutate_change_rate
      (@possible_elements || @data).sample
    else
      val
    end
  end
  create_new_solution(new_data)
end