Skip to content

Commit

Permalink
Added an example of evolving a constant number with integers 0-9 and …
Browse files Browse the repository at this point in the history
…addition, subtraction, multiplication, and protected division.
  • Loading branch information
Larry Diehl committed Nov 6, 2008
1 parent 4e0a72c commit e1a76c7
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 2 deletions.
26 changes: 26 additions & 0 deletions examples/constant.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
require File.join(File.dirname(__FILE__), "..", "revolve")

class Integer
def protected_division(divisor)
self / divisor rescue 1
end
end

population = Revolve::Population.initialized( 200, {
:program_size => 10,
:instructions => [1, 2, 3, 4, 5, 6, 7, 8, 9,
Revolve::Method.new(:+), Revolve::Method.new(:-),
Revolve::Method.new(:*), Revolve::Method.new(:protected_division)],
:max_generations => 500,
:fitness_cases => [ lambda{|program| program.run.to_i - 120 } ],
:fitness_combinator => lambda{|cases| cases.first.abs },
:crossover_chance => 0.6,
:mutation_chance => 0.3
})

population.evolve!

puts "Generations: #{population.generation}"
puts "Fitness: #{population.fitness(population.fittest_program)}"
puts "Program:\n#{population.fittest_program.inspect}"
puts "Output: #{population.fittest_program.run}"
4 changes: 4 additions & 0 deletions lib/method.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,9 @@ def call!
target.method(name).arity.times { arguments.push(stack.pop) }
stack.push( target.send(*arguments) ).last
end

def inspect
"(:#{name} method)"
end
end
end
5 changes: 3 additions & 2 deletions lib/population.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@ def self.initialized(size, parameters)

def evolve!
update_fittest_program!
max_generations.times do
max_generations.times do
break if fitness(fittest_program) == 0
evolve_generation!
update_fittest_program!
update_fittest_program!
end
fittest_program
end
Expand Down
13 changes: 13 additions & 0 deletions spec/method/inspect_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
require File.join(File.dirname(__FILE__), "..", "spec_helper")

module Revolve

describe Method, "#inspect" do
before { @method = Method.new(:+) }

it "should be the name wrapped in 'method'" do
@method.inspect.should == "(:+ method)"
end
end

end

0 comments on commit e1a76c7

Please sign in to comment.