[R] Listing all binary trees of an ordinal set
David Winsemius
dwinsemius at comcast.net
Tue Jun 19 01:02:59 CEST 2012
On Jun 18, 2012, at 5:25 PM, elmo wrote:
> 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:
Please do not cross-post (but DO read the Posting Guide where this was
is requested). You have already gotten an answer on StackOverflow.
--
David.
>
> 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.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list