Class: Wallace::Operators::TwoPointCrossoverOperator

Inherits:
Wallace::Operator show all
Defined in:
lib/operators/two_point_crossover_operation.rb

Overview

Two-point crossover takes two individuals, A and B, as parents, and produces two children by swapping the substrings between loci, X and Y.

Two crossover points, X and Y, are chosen such that X and Y both lie within the bounds of A and B and that X < Y. The substrings A and B are swapped to produce two (potentially) new children strings.

Instance Method Summary collapse

Methods inherited from Wallace::Operator

#initialize, #produce

Constructor Details

This class inherits a constructor from Wallace::Operator

Instance Method Details

#operate(rng, inputs) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/operators/two_point_crossover_operation.rb', line 11

def operate(rng, inputs)

  # Ensure that the individuals are longer than length 2!
  return inputs if inputs[0].length <= 2 or inputs[1].length <= 2

  # Calculate the crossover points X and Y then swap the substrings
  # between A and B at those loci.
  x = rng.rand((1...([inputs[0].length, inputs[1].length].min-1)))
  y = rng.rand((x...([inputs[0].length, inputs[1].length].min)))

  # Unfortunately []= can not be performed in parallel so we must
  # find and store a substring before swapping them.
  t = inputs[0][x...y]
  inputs[0][x...y] = inputs[1][x...y]
  inputs[1][x...y] = t

  return inputs

end