Class: UniformReplaceStrategy

Inherits:
ReplaceStrategy show all
Defined in:
lib/gimuby/genetic/population/replace_strategy/uniform_replace_strategy.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeUniformReplaceStrategy

Returns a new instance of UniformReplaceStrategy.



5
6
7
# File 'lib/gimuby/genetic/population/replace_strategy/uniform_replace_strategy.rb', line 5

def initialize
  @replace_proportion = 50.to_f / 100.to_f
end

Instance Attribute Details

#replace_proportionObject

Returns the value of attribute replace_proportion.



9
10
11
# File 'lib/gimuby/genetic/population/replace_strategy/uniform_replace_strategy.rb', line 9

def replace_proportion
  @replace_proportion
end

Instance Method Details

#replace(population, selected = nil) ⇒ Object



11
12
13
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
# File 'lib/gimuby/genetic/population/replace_strategy/uniform_replace_strategy.rb', line 11

def replace(population, selected = nil)
  solutions = population.solutions.clone

  wished_length = solutions.length
  solutions.shuffle!
  if selected.nil?
    selected = population.pick
  end
  number_to_remove = (wished_length * @replace_proportion).floor
  if number_to_remove == wished_length
    number_to_remove -= 1
  end
  solutions.slice!(-number_to_remove, number_to_remove)

  while solutions.length < wished_length
    begin
      random_index1 = rand(selected.length)
      random_index2 = rand(selected.length)
    end while ((random_index1 == random_index2) && (selected.length != 1))
    new_solutions = reproduce(selected[random_index1],
                              selected[random_index2])
    new_solutions.each do |new_solution|
      solutions.push(new_solution)
    end
  end

  solutions.slice!(wished_length) # we could have one that should be dropped
  solutions
end