Skip to content

Instantly share code, notes, and snippets.

@Yuemashi
Last active July 7, 2016 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yuemashi/e73ac06a2e3ab37dd3d0c126c49ea376 to your computer and use it in GitHub Desktop.
Save Yuemashi/e73ac06a2e3ab37dd3d0c126c49ea376 to your computer and use it in GitHub Desktop.
Genotype = -> size {
(1..size).map{rand (0..1)} }
Population = -> individualSize, popSize {
(0..popSize).map{Genotype[individualSize]} }
fitness = -> genotype {
genotype.inject(:+) }
crossover = -> parents, position {
[] << parents[0].take(position) + parents[1].drop(position) <<
parents[1].take(position) + parents[0].drop(position) }
mutate = -> individual, position, genotypeDefinition {
individual[position] = genotypeDefinition.curry(1)
individual.flatten }
selection = -> population {
(population + population).sort_by{ |n| -fitness[n]}.take(population.length) }
nextGeneration = -> population {
population = selection[population]
elite = population.take(1).flatten
nextPop = []
(0..population.length / 2 - 1)
.each{crossover[
[] << population[rand(population.length - 1)] << population[rand(population.length - 1)],
rand(population[1].length - 1)]
.map{|g| nextPop << g}}
nextPop = nextPop
.map{|n| (0..n.length - 1)
.map{|p| rand(0.0..1.0) < 0.05 ? Genotype[1] : n[p] }.flatten }
nextPop.sort_by { |n| -fitness[n]}.take(nextPop.length - 1) << elite }
pop = Population[50,100]
pop.sort_by { |n| -fitness[n]}.take(1)
=>[[1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1]]
(0..100).each{pop = nextGeneration[pop]}
pop.sort_by { |n| -fitness[n]}.take(1)}
=>[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment