Skip to content

Instantly share code, notes, and snippets.

@ldunn
Created September 4, 2010 01:02
Show Gist options
  • Select an option

  • Save ldunn/564791 to your computer and use it in GitHub Desktop.

Select an option

Save ldunn/564791 to your computer and use it in GitHub Desktop.
require "node"
function adjusted_fitness(standard_fitness)
local denominator = 1 + standard_fitness
return 1 / denominator
end
function generate_full(functions, terminals, max_depth)
local root = nil
if max_depth > 1 then
-- Keep going!
local node = functions[math.random(table.getn(functions))]
root = new_node(node.arity, node.value)
else
-- Time for a terminal
local node = terminals[math.random(table.getn(terminals))]
root = new_node(node.arity, node.value)
end
-- Assign child nodes recursively
if root.arity > 0 then
for i = 1,root.arity do
add_child(root, generate_full(functions, terminals, max_depth - 1))
end
end
return root
end
function generate_grow(functions, terminals, max_depth)
local root = nil
if max_depth > 1 then
-- Function or terminal?
choose_func = math.random(2) == 1
if choose_func then
node = functions[math.random(table.getn(functions))]
root = new_node(node.arity, node.value)
else
node = terminals[math.random(table.getn(terminals))]
root = new_node(node.arity, node.value)
end
else
-- Choose a terminal
node = terminals[math.random(table.getn(terminals))]
root = new_node(node.arity, node.value)
end
if root.arity > 0 then
for i = 1,root.arity do
add_child(root, generate_grow(functions, terminals, max_depth - 1))
end
end
return root
end
function random_select_subtree(root)
local keep_going = math.random(2) == 1
if keep_going then
if root.child_count > 0 then
local next_node = root.children[math.random(root.child_count)-1]
return random_select_subtree(next_node)
else
return root
end
else
return root
end
end
function subtree_crossover(father, mother)
local offspring = clone_node(mother)
replace_child(offspring, math.random(offspring.child_count)-1, random_select_subtree(father))
return offspring
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment