Module: RouletteSelection

Defined in:
lib/charlie/selection.rb

Overview

Roulette selection without replacement. Probability of individual i being selected is fitness(i) / sum fitness(1..population size)

Instance Method Summary collapse

Instance Method Details

#next_generation(population) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/charlie/selection.rb', line 45

def next_generation(population)
  partial_sum = []
  sum = population.inject(0){|a,b| cs = a + b.fitness; partial_sum << cs; cs }

  new_pop = []
  while new_pop.size < population.size
    i1,i2 = [0,0].map{ 
      r = rand * sum
      partial_sum.index partial_sum.find{|x| x > r }
    } until i1!=i2  # no replacement, except when this fails
    new_pop += yield(population[i1],population[i2])
  end
  new_pop.pop until new_pop.size == population.size
  new_pop
end