Created
December 16, 2013 09:27
-
-
Save Mon-Ouie/7984398 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pop_with_fitness = population.map { |individual| | |
[individual, individual.fitness] | |
} | |
Array.new(breeding_pool_size) do | |
norm = pop_with_fitness.map(&:last).max | |
if norm.zero? | |
pop_with_fitness.pop.first | |
else | |
minimal_fitness = rand | |
i = pop_with_fitness.find_index { |individual, fitness| | |
fitness.fdiv(norm) >= minimal_fitness | |
} | |
pop_with_fitness.delete_at(i).first | |
end | |
end | |
end | |
end | |
module TournamentSelection | |
attr_accessor :tournament_size | |
attr_accessor :base_probabiltty | |
def select(population, breeding_pool_size) | |
pop_with_fitness = population.map { |individual| | |
[individual, individual.fitness] | |
}.sort_by(&:last) | |
base_probability = @base_probability || 1 | |
tournament_size = @tournament_size || 1 | |
Array.new(breeding_pool_size) do | |
tournament = pop_with_fitness.sample(tournament_size).sort_by(&:last) | |
chosen = tournament.reverse_each.find { |individual, _| p >= rand } | |
chosen ||= tournament.first | |
pop_with_fitness.delete(chosen) | |
chosen.first | |
end | |
end | |
end | |
end | |
class Problem | |
def self.random_population(n) | |
Array.new(n) { new(100*rand, 100*rand) } | |
end | |
def initialize(x, y) | |
@x = x | |
@y = y | |
end | |
attr_accessor :x, :y | |
def fitness | |
-(x - 5) ** 2 + (y - 7)**2 + 2*x + 3*y + 1000 | |
end | |
end | |
class Solution1 < Problem | |
extend Genetics::RouletteWheelSelecion | |
def self.test | |
select(random_population(20), 5) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment