Class: Algorithms::GeneticAlgorithm::PermutationSolution

Inherits:
Object
  • Object
show all
Includes:
Solution
Defined in:
lib/algorithms/genetic_algorithm/solutions/permutation.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) ⇒ PermutationSolution

Returns a new instance of PermutationSolution.



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

def initialize(array)
  @data = array
end

Instance Method Details

#crossover(other_solution) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/algorithms/genetic_algorithm/solutions/permutation.rb', line 12

def crossover(other_solution)
  sampled_indices = @data.each_index.to_a.sample(@data.size / 2)
  sampled_elements = sampled_indices.map { |i| @data[i] }
  elements_from_other = other_solution.data.select { |el| sampled_elements.include?(el) }
  new_data = @data.dup
  sampled_indices.zip(elements_from_other).each do |idx, el|
    new_data[idx] = el
  end
  create_new_solution(new_data)
end

#mutateObject



8
9
10
# File 'lib/algorithms/genetic_algorithm/solutions/permutation.rb', line 8

def mutate
  create_new_solution(@data.shuffle)
end