Class: Wallace::Selectors::TournamentSelector

Inherits:
Wallace::Selector show all
Defined in:
lib/selectors/tournament_selector.rb

Instance Method Summary collapse

Methods inherited from Wallace::Selector

#prepare

Constructor Details

#initialize(opts = {}) ⇒ TournamentSelector

Constructs a new tournament selector.

Arguments

  • opts, a hash of keyword options for this method. -> size, the size of the tournament. (default = 3). -> pick_best, flag indicating if the best individual in the tournament should win.

Raises:

  • (ArgumentError)


11
12
13
14
15
16
# File 'lib/selectors/tournament_selector.rb', line 11

def initialize(opts = {})
  @size = opts[:size] || 3
  pick_best = opts[:pick_best] || true
  @winning_condition = pick_best ? -1 : 1
  raise ArgumentError, "Tournament size must be greater than 1." if @size < 2
end

Instance Method Details

#produce(rng, candidates) ⇒ Object

Random samples a number (equal to the tournament size) of individuals from the list of candidates, and returns the best or worst (depending on the selector parameters).

Arguments

  • rng, random number generator to use to select index of individual.

Parameters:

  • rng, random number generator to use to select index of individual.

  • candidates, the list of candidates for inclusion within the tournament.

Returns: The winning individual of the tournament (whether best or worst).



31
32
33
34
# File 'lib/selectors/tournament_selector.rb', line 31

def produce(rng, candidates)
  tournament = candidates.sample(@size, random: rng)
  return @winning_condition ? tournament.min : tournament.max
end