[R] Listing all binary trees of an ordinal set
elmo
elmoryl at gmail.com
Mon Jun 18 23:25:51 CEST 2012
Hi all,
I'm new to R, have been reading books and trying to get started coding too.
The first thing of substance I've been trying to do is to create a function
to return a list of all binary trees of a list of ordinals. So, for
example, an input of list(3,1,2,4) would return:
list(list(1, list(2, list(3, 4))),
list(1, list(list(2, 3), 4)),
list(list(1, 2), list(3, 4)),
list(list(1, list(2, 3)), 4),
list(list(list(1, 2), 3), 4))
I've been trying recursions but nothing I've written has been both complete
and correct in the final formatting, and I'm sort of clueless when it comes
to recursive wrappers. For example, one function I wrote,
g=function(x) {
len.x = length(x);
if (len.x > 2)
{
y=list()
for (i in 1:(len.x-1))
y[[i]] = list(g(x[1:i]),g(x[-i:-1]))
return(y)
}
else return(x)
}
trim = function(x) {
for (i in 1:length(x)) {
if ((length(x[[i]]) == 1) && is.list(x[[i]]))
x[[i]] = x[[i]][[1]]
}
return(x)
}
findBinTreesOrd=function(x) {
x.lst = sort(unlist(x))
all.bin.trees = g(x.lst)
trim(all.bin.trees)
}
returns the trees in a compact, recursively nested form that I haven't found
a way to expand to the format that I desire. Any help in either writing a
wrapper for that or a different approach to achieve what I'm trying to get
would be greatly appreciated--again, I'm quite new to R and am still shaky
with the powers and constraints that come with it.
LM
--
View this message in context: http://r.789695.n4.nabble.com/Listing-all-binary-trees-of-an-ordinal-set-tp4633753.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list