Class: Wallace::Operators::CycleCrossoverOperator
- Inherits:
-
Wallace::Operator
- Object
- Wallace::Operator
- Wallace::Operators::CycleCrossoverOperator
- Defined in:
- lib/operators/cycle_crossover_operation.rb
Overview
Credit: Oliver, I. M., Smith, D. J., & Holland, J. R. C. (1987). A study of permutation crossover operators on the traveling salesman problem. In Proceedings of the second international conference. on genetic algorithms (ICGA’87) (pp. 224–230). Cambridge, MA:Massachusetts Institute of Technology
Defined Under Namespace
Classes: HashPair
Instance Method Summary collapse
Methods inherited from Wallace::Operator
Constructor Details
This class inherits a constructor from Wallace::Operator
Instance Method Details
#operate(rng, parents) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/operators/cycle_crossover_operation.rb', line 14 def operate(rng, parents) # http://www.rubicite.com/Tutorials/GeneticAlgorithms/CrossoverOperators/CycleCrossoverOperator.aspx length = parents[0].length children = [ Array.new(length) { nil }, Array.new(length) { nil } ] # Generate a hash to indicate when certain indices have been # used in a cycle. used = Hash[(0...length).map { |v| [v, false] }] # REVERSE ENGINEER. helper = Hash[(0...length).map { |v| temp_pair = HashPair.new( parents[0][v], parents[1][v], v ) [parents[1][v], temp_pair] }] cycles = [] (0...length).each do |j| cyc = [] unless used[j] then cyc_start = j temp_pair = helper[parents[0][cyc_start]] cyc << temp_pair used[temp_pair.i2] = true until temp_pair.i2 == cyc_start temp_pair = helper[parents[0][temp_pair.i2]] cyc << temp_pair used[temp_pair.i2] = true end end cycles << cyc end # Alternating cycles. cycles.each_with_index do |cyc, num| if (num % 2) == 0 cyc.each do |temp_pair| children[0][temp_pair.i2] = temp_pair.v1 children[1][temp_pair.i2] = temp_pair.v2 end else cyc.each do |temp_pair| children[0][temp_pair.i2] = temp_pair.v2 children[1][temp_pair.i2] = temp_pair.v1 end end end return children end |