Skip to content

Instantly share code, notes, and snippets.

@gluc
Last active September 29, 2015 03:06
Show Gist options
  • Save gluc/1d8c9d9f9dcfbb25494d to your computer and use it in GitHub Desktop.
Save gluc/1d8c9d9f9dcfbb25494d to your computer and use it in GitHub Desktop.
Genetics Crossover
library(data.tree)
CreateCrossoverRandomTree <- function(n, treeId) {
tree <- CreateRandomTree(n)
tree$Set(treeId = treeId)
tree$Set(id = 1:tree$totalCount)
return (tree)
}
t1 <- CreateCrossoverRandomTree(20, 1)
t2 <- CreateCrossoverRandomTree(20, 2)
#node to be replaced (random node in your case, here just arbitrarily node with name "5"):
t1n <- Traverse(t1, filterFun = function(x) x$name == "5")[[1]]
#replace by
t2n <- Traverse(t2, filterFun = function(x) x$name == "7")[[1]]
#clone in case you want to keep the original tree
t2n <- Clone(t2n)
t2n$parent <- NULL
t1p <- t1n$parent
#remove the original sub-tree
t1p$RemoveChild(t1n$name)
#add the copy from t2
t1p$AddChildNode(t2n)
#check that everything went ok
print(t1, "treeId")
@ciniro
Copy link

ciniro commented Sep 29, 2015

I used this function for performing crossover on sintatic trees for genetic programming. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment