Skip to content

Instantly share code, notes, and snippets.

@arwagner
Created October 24, 2011 01:06
Show Gist options
  • Save arwagner/1308151 to your computer and use it in GitHub Desktop.
Save arwagner/1308151 to your computer and use it in GitHub Desktop.
Genetic algorithm
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