Created
May 13, 2014 19:35
-
-
Save marostr/2773cb393e9648b22d1e 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
| GENE_SIZE = 64 | |
| MUTATION_RATE = 0.001 | |
| #MUTATION_RATE = 0.01 | |
| class Chromosome | |
| attr_accessor :genes | |
| def initialize genes = nil | |
| genes ? self.genes = genes : self.genes = (1..GENE_SIZE).map{ rand(3) }.join | |
| end | |
| def fitness | |
| genes.count('2') + genes.count('1')/2 | |
| end | |
| def mutate! | |
| mutated = [] | |
| genes.split('').each do |gene| | |
| if rand < MUTATION_RATE | |
| gene += 1 | |
| gene %= 3 | |
| end | |
| end | |
| mutated << gene | |
| self.genes = mutated.join | |
| end | |
| def & other | |
| split = rand(genes.length + 1) | |
| child = genes[0, split] + other.genes[split, other.genes.length] | |
| end | |
| def to_s | |
| genes | |
| end | |
| end | |
| c1 = Chromosome.new | |
| c2 = Chromosome.new | |
| puts 'Chromosome 1' | |
| puts c1 | |
| puts 'Fitness' | |
| puts c1.fitness | |
| puts '----' | |
| puts 'Chromosome 2' | |
| puts c2 | |
| puts 'Fitness' | |
| puts c2.fitness | |
| puts '----' | |
| child = Chromosome.new c1 & c2 | |
| puts 'Child' | |
| puts child | |
| puts 'Fitness' | |
| puts child.fitness |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment