Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
diff --git a/generation.rb b/generation.rb
index c191dcd..238f8e3 100644
--- a/generation.rb
+++ b/generation.rb
@@ -21,9 +21,9 @@ class Animal
end
def mate(other)
- @genes = (@genes[0...16] + other.genes[0...16])
- mutate
- self
+ child = Animal.new(@genes[0...16] + other.genes[0...16])
+ child.mutate
+ child
end
def is_spartan?
@@ -32,6 +32,8 @@ class Animal
end
class Generation
+ NUM_OFFSPRING = 20
+
attr_reader :animals
def initialize (animals=[], gen_size = 10)
@@ -43,23 +45,22 @@ class Generation
end
def mate
@animals = [].tap {|a|
- @gen_size.times{
+ NUM_OFFSPRING.times{
a << @animals[rand @gen_size].mate(@animals[rand @gen_size])
}
}
end
def alphas
- @animals.sort! {|a, b| b.calc_fitness <=> a.calc_fitness}.first(@gen_size)
+ @animals = @animals.sort {|a, b| b.calc_fitness <=> a.calc_fitness}.first(@gen_size)
end
def include_spartans?
- @animals.include? Array.new(32).fill 1 #perfect genes
+ @animals.map(&:genes).include? Array.new(32).fill 1 #perfect genes
end
def output
@animals.each {|an| print "#{an.genes.join}: #{an.calc_fitness}\n"}
end
end
-NUM_OFFSPRING = 10
gen = Generation.new
gen.seed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment