0

I'm trying to implement a ternary search tree in R.

Here's the logic I'm trying to implement:

A vector will be "tiered" by designating each level of the tree as the next 3^somepower of cells after the existing tier. So tier 1 will be the first cell, tier 2 will be cells 2-4, tier 3 will be cells 5-13, tier 4 will be cells 14-40, tier 5 will be cells 41-122, and so on.

I want my code to do the following:

1) Take a vector, and an object obj to insert in the tree. In practice obj will be a number.

2) If the slot I'm trying to go into is full, jump down to the next tier, according to the rules:

2a) If obj is < than the occupied cell, go down to the left cell in the next level, of the three-cell-block "directly below" it.

2b) If obj is == the occupied cell, go down to the center cell of the three-cell-block "directly below" it.

2c) If 'obj' is > the occupied cell, go down to the rightmost cell of the three-cell-block "directly below it".

I drew a diagram of what I want the output to be if I put in the numbers 34,42,15,24,16, 34,52,32,42,19,21,16,54,60,55. I included the code that does something, but I don't understand exactly what it's doing. I just know that it isn't doing what I want to do.

Thanks for your help.

Desired output:

enter image description here

My code:

put<-function(obj, Tree,pow=0,offset=1,arity=3)
{
  level<-arity^pow

   if (is.na(Tree[level])){
      Tree[level+offset-1]<-obj
      return(Tree)
  } else {
  if (obj<Tree[level]) {
      put(obj,Tree,pow+1,offset=0)
  } else {
  if (obj == Tree[level]){
      put(obj,Tree,pow+1,offset=1)
  } else {
  if (obj > Tree[level]){
      put(obj,Tree,pow+1,offset=2)
  }}}}
}
BeforeTree<-c(34,42,15,24,16,
              34,52,32,42,19,21,16,54,60,55)

Tree<-NA

for (idx in 1:(length(BeforeTree)))
{Tree<-put(BeforeTree[idx],Tree)}
(Tree)
GFauxPas
  • 299
  • 1
  • 14
  • 1
    Perhaps you could take some existing open source code for ternary search trees in R and modify that code to fit your needs https://cran.r-project.org/web/packages/TSTr/vignettes/TSTr.html – Hack-R Dec 13 '16 at 16:53
  • @Hack-R that would be much easier, but this is for an assignment. How do I see the source code behind those built-ins? – GFauxPas Dec 13 '16 at 16:57
  • It's on Github https://github.com/cran/TSTr – Hack-R Dec 13 '16 at 17:25
  • @Hack-R Thanks. I'd still like to know whats wrong with my code, though. – GFauxPas Dec 13 '16 at 17:58

0 Answers0