Created
October 24, 2011 01:06
-
-
Save arwagner/1308151 to your computer and use it in GitHub Desktop.
Genetic algorithm
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
class ProceduralFiveDigits | |
def initialize | |
@new_population = Array.new(100) { generate_individual } | |
reset | |
end | |
def evolve | |
1000.times do | |
100.times do | |
@parent_a, @parent_b = [pick_individual, pick_individual] | |
@new_population.push cross_parents | |
end | |
reset | |
end | |
best_individual | |
end | |
private | |
def generate_individual | |
Array.new(5) { (0..9).to_a.sample } | |
end | |
def pick_individual | |
fitness_left = @total_fitness | |
@population.find {|i| fitness_left -= fitness(i); fitness_left <= 0 } | |
end | |
def cross_parents | |
point = rand(5) | |
@parent_a.first(point) + @parent_b.last(5-point) | |
end | |
def best_individual | |
@population.first | |
end | |
def reset | |
@population = @new_population.sort {|a,b| fitness(a) <=> fitness(b) } | |
@new_population = [] | |
@total_fitness = @population.inject(0) {|s,i| s + fitness(i) } | |
end | |
def fitness(i) | |
i.inject(:+) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment