Skip to content

Instantly share code, notes, and snippets.

@JanDupal
Created February 8, 2012 21:24
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 JanDupal/1773998 to your computer and use it in GitHub Desktop.
Save JanDupal/1773998 to your computer and use it in GitHub Desktop.
Resistor combinations (serial, parallel) using GP ( https://github.com/phorsfall/genetics/ )
$:.unshift("lib")
require "genetics"
require "pp"
class Resist < Tree
TARGET = 215
literals [50, 100, 500]
function(:para) { |a,b| (a*b)/(a+b) }
function(:ser) { |a,b| a + b }
def fitness
@fitness ||= begin
value = (TARGET - evaluate).abs + 5*leaf_count + ballance
value
end
end
def leaf_count(node = genes)
node[0] == :call ? (node[2..-1].map { |n| leaf_count(n) }.inject(:+)) : 1
end
def ballance(node = genes)
return 0 if node[0] != :call
depths = node[2..-1].map { |n| depth(n) } || [0]
depths.max - depths.min
end
end
population = Population.new(Resist, :select_with => Tournament, :size => 50)
population.evolve(1000) do |g|
print "."
$stdout.flush
end
winner = population.fittest
puts
pp winner.genes
puts
puts "Value: #{winner.evaluate} Ohms, resistors: #{winner.leaf_count}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment