Created
September 30, 2011 15:30
-
-
Save tcrayford/1254115 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Generation < Struct.new(:members) | |
def to_a | |
members | |
end | |
def sort | |
members.sort! do |a,b| | |
a.score <=> b.score | |
end | |
self | |
end | |
def log(logging_enabled) | |
if logging_enabled | |
members.each do |individual| | |
puts individual.to_s | |
end | |
end | |
end | |
end | |
class PopulationControl | |
def initialize(population_size, target, logging_enabled) | |
@target = target | |
@logging_enabled = logging_enabled | |
@population_size = population_size | |
@population = [] | |
population_size.times do | |
@population.push Reproducer.new(target.length) | |
end | |
end | |
def next_round | |
puts "----" | |
generation = Generation.new(populate_generation).sort | |
generation.log(@logging_enabled) | |
cull_population(generation) | |
end | |
def cull_population(generation) | |
generation.to_a.each_index do |index| | |
replace_reproducer(index) | |
end | |
end | |
def populate_generation | |
@population.map do |reproducer| | |
Individual.new(reproducer, @target) | |
end | |
end | |
def replace_reproducer(index) | |
if should_be_culled?(index) | |
@population[index] = Reproducer.new(@target.length) | |
end | |
end | |
def should_be_culled?(index) | |
rand(@population_size) <= index | |
end | |
end | |
class Individual < Struct.new(:reproducer, :target) | |
def score | |
score = 0 | |
reproducer.output.each_index do |index| | |
score += (target[index] - reproducer.output[index]).abs | |
end | |
end | |
def to_s | |
"#{reproducer.to_s} #{score}" | |
end | |
end | |
class Reproducer | |
attr_reader :output | |
def initialize(output_length) | |
@output = [] | |
output_length.times { @output.push(32 + rand(94)) } | |
end | |
def to_s | |
out = '' | |
output.each {|c| out += c.chr} | |
return out | |
end | |
end | |
control = PopulationControl.new(10, "Hello World!", true) | |
10.times do | |
control.next_round | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment