[R] Break during the recursion?
hadley wickham
h.wickham at gmail.com
Sun Jul 15 17:58:44 CEST 2007
On 7/15/07, Duncan Murdoch <murdoch at stats.uwo.ca> wrote:
> On 15/07/2007 11:36 AM, Atte Tenkanen wrote:
> >> On 15/07/2007 10:33 AM, Atte Tenkanen wrote:
> >>>> On 15/07/2007 10:06 AM, Atte Tenkanen wrote:
> >>>>> Hi,
> >>>>>
> >>>>> Is it possible to break using if-condition during the recursive
> >>>> function?
> >>>> You can do
> >>>>
> >>>> if (condition) return(value)
> >>>>
> >>>>> Here is a function which almost works. It is for inorder-tree-
> >>>> walk.
> >>>>> iotw<-function(v,i,Stack,Indexes) # input: a vector and the
> >> first
> >>>> index (1), Stack=c(), Indexes=c().
> >>>>> {
> >>>>> print(Indexes)
> >>>>> # if (sum(i)==0) break # Doesn't work...
> >>>> if (sum(i)==0) return(NULL)
> >>>>
> >>>> should work.
> >>>>
> >>>> Duncan Murdoch
> >>> Hmm - - - I'd like to save the Indexes-vector (in the example
> >> c(8,4,9,2,10,5,11,1,3)) and stop, when it is ready.
> >>
> >> This seems more like a problem with the design of your function
> >> than a
> >> question about R. I can't really help you with that, because your
> >> description of the problem doesn't make sense to me. What does it
> >> mean
> >> to do an inorder tree walk on something that isn't a tree?
> >>
> >> Duncan Murdoch
> >
> > The symbols in vector v have been originally derived from "tree". See
> >
> > http://users.utu.fi/attenka/Tree.jpg
> >
> > But perhaps there's another way to do this, for instance by using loops and if-conditions?
>
> Or perhaps by doing the tree walk on the tree, before you collapse it
> into a vector.
If it's a binary tree with n levels, I think you should be able to
generate the positions more directly, depending on how the tree has
been flattened. Binary heaps work this way, so that might be a good
place to start. See http://en.wikipedia.org/wiki/Binary_heap,
particularly heap implementation.
Hadley
More information about the R-help
mailing list