Class: Algorithms::GeneticAlgorithm::CombinationSolution

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

Instance Attribute Summary

Attributes included from Solution

#data

Instance Method Summary collapse

Methods included from Solution

#create_new_solution, #valid?

Constructor Details

#initialize(possible_elements, size, data: possible_elements.sample(size)) ⇒ CombinationSolution

Returns a new instance of CombinationSolution.



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

def initialize(possible_elements, size, data: possible_elements.sample(size))
  @data, @possible_elements, @size = Set.new(data), possible_elements, size
end

Instance Method Details

#crossover(other_solution) ⇒ Object



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

def crossover(other_solution)
  size = @data.size
  common = @data & other_solution.data
  sym_diff = @data ^ other_solution.data
  sampled_sym_diff = Set.new(sym_diff.to_a.sample(size - common.size))
  new_data = common.union(sampled_sym_diff)
  create_new_solution(new_data)
end

#mutateObject



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

def mutate
  create_new_solution(Set.new(@possible_elements.sample(@size)))
end