Ternary Search Tree Implementation in R - r

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:
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)

Related

R function to check each element and its related children elements to add a result to a list

Suppose we have given dataframe in R. By 0--7, it means it is taking integer values from 0-7 i.e. 0,1,2,3,4,5,6,7.
I am interested in making a function such that
If a[1,1]>alpha, it goes and checks its children i.e. 0--7 consists of a[1,2] and a[2,2].
So,
{a[2,1]>alpha
{a[4,1]>alpha
{a[5,1]>alpha
ps=list.append(0)
else ps=list.append(1)
}}}
Here, alpha is a a threshold. The ps is appended from values of 0 to 15 based on this criteria.
My code is
{for (i in 1:2)
{ if (a[j,i]>alpha)
{if (i%%2==1}
{j=j*2
if (a[j,i]>alpha
###here i want to go recursively i think and where and how should i add append values to the list
if a[j,i+1]>alpha}
if{i%%2==0}
{}
}}
I am stuck and confused at the same time. Any help or advices would be greatly appreciated.
Thanks

2d array gamemaker2 studio

Experienced programmer playing around with Gamemaker2 Studio.
Trying to draw some random squares on the screen using a 2D array to store the "map"
Step 1 : declare a 2D array MyMap[25,25] this works
Step 2 : Set 100 random locations in Map[]=1 this works
I get a crash when I try to look up the values I have stored in the array.
Its crashing with:
**Execution Error - Variable Index [3,14] out of range [26,14] **
So it looks like it is trying to read 26 element, when you can see from my code the for next loop only goes to 20 and the array bound is 25.
Oddly enough it does the first two loops just fine?
Looking like a bug, I've spent so much time trying to work it out, anyone got an idea what is going on?
var tx=0;
var ty=0;
var t=0;
MyMap[25,25]=99; **// Works**
for( t=1; t<100; t+=1 ) **// Works**
{
MyMap[random(20),random(15)]=1
}
for( tx=1; tx<20; tx+=1 )
{
for( ty=1; ty<15; ty+=1 )
{
show_debug_message(string(tx) + ":" + string(ty))
t = MyMap[tx,ty]; /// **<---- Crashes Here**
if t=1 then {draw_rectangle(tx*32,ty*32,tx*32+32,ty*32+32,false) }
}
}
The line MyMap[random(20),random(15)]=1 does not initialize values in the entire array, creating a sparse array(where some elements do not exist).
The line MyMap[25,25]=99;
Should read:
for( tx=1; tx<20; tx+=1 )
{
for( ty=1; ty<15; ty+=1 )
{
MyMap[tx,ty]=99;
}
}
This will pre-initialize the all of the array values to 99. Filling out the array.
Then you can randomly assign the ones. (You will probably get less than 100 ones the due to duplicates in the random function and the random returning zeros.)
You should have the above code in the Create Event, or in another single fire or controlled fire event, and move the loops for the draw into the Draw Event.
All draw calls should be in the Draw Event. If the entire block were in Draw, it would randomize the blocks each step.

R: Iterating Over the List

I am trying to implement following algorithm in R:
Iterate(Cell: top)
While (top != null)
Print top.Value
top = top.Next
End While
End Iterate
Basically, given a list, the algorithm should break as soon as it hits 'null' even when the list is not over.
myls<-list('africa','america south','asia','antarctica','australasia',NULL,'europe','america north')
I had to add a for loop for using is.null() function, but following code is disaster and I need your help to fix it.
Cell <- function(top) {
#This algorithm examines every cell in the linked list, so if the list contains N cells,
#it has run time O(N).
for (i in 1:length(top)){
while(is.null(top[[i]]) !=TRUE){
print(top)
top = next(top)
}
}
}
You may run this function using:
Cell(myls)
You were close but there is no need to use for(...) in this
construction.
Cell <- function(top){
i = 1
while(i <= length(top) && !is.null(top[[i]])){
print(top[[i]])
i = i + 1
}
}
As you see I've added one extra condition to the while loop: i <= length(top) this is to make sure you don't go beyond the length of the
list in case there no null items.
However you can use a for loop with this construction:
Cell <- function(top){
for(i in 1:length(top)){
if(is.null(top[[i]])) break
print(top[[i]])
}
}
Alternatively you can use this code without a for/while construction:
myls[1:(which(sapply(myls, is.null))[1]-1)]
Check this out: It runs one by one for all the values in myls and prints them but If it encounters NULL value it breaks.
for (val in myls) {
if (is.null(val)){
break
}
print(val)
}
Let me know in case of any query.

Assigning Values within a dynamically named matrix in R

I am struggling with a loop in R where I have to use dynamic variable names (which I am told is a bad idea from the other posts about dynamic variable names, but I am pretty sure that I need to based on my file structure). Each folder for which the loop enters, there is a different number of files.
The dynamic variable names contain matrices and I need to look in each row/column of the matrix and output a new matrix.
Streamlined example:
var 1 is a matrix(0,40,40)
var 2 is a matrix(0,45,45)
var 3 is a matrix(0,40,40)
For (f in 1:(length of var3s)) # the number of files in the folder, in each folder:
For (g in 1: ncol(var1)) {
For (h in 1: nrow(var1)) {
if (var 1[g,h]>4 & var 2[g,h]<1)
{ var3[f] [g,h]<-1} # <- you cannot do this, but this is ultimately what I want
}
}
I want to take the f-th variable matrix from variable 3's list and assign a value to the location at [g,h]
I've done this before with real variable names, but I am struggling with adding the dynamic element. This is what it looks like and the errors I'm getting.
for (f in 1:(length(LD139_040))){
assign(paste0("LD139_040s",f),
matrix(0,nrow(eval(parse(text=paste0("B139_040",f)))),
ncol(eval(parse(text=paste0("B139_040",f)))))) # this effectively creates my new matrix (var3 above) the size I need based on the files above
for (g in 1:(ncol(eval(parse(text=paste0("B139_040",f)))))){
for (h in 1:(nrow(eval(parse(text=paste0("B139_040",f)))))){
if (S139_040[g,h]>10 &
(assign(paste0("LD139_040",f), as.matrix(raster(LD139_040[f]))))[g,h]>.295 &
(assign(paste0("LD139_040",f), as.matrix(raster(LD139_040[f]))))[g,h]<.33 &
(assign(paste0("B139_040",f), as.matrix(raster(Blue139_040[f]))))[g,h]<180)
# this section also works and will give me a t/f at each location [g,h]
# if true, assign the value 1 to the new matrix LD139_040 at f
{assign(paste0("LD139_040s", f)[g,h], 1)}
}
}
}
I have tried a variety of combinations of eval and assign to organize the last statement, and I get errors such as 'invalid first assignment', incorrect number of dimensions, and target of assignment expands to non-language object.
Thanks for your help!
R version 3.1.1 "Sock it to Me" with library(raster)
This did not require dynamic variable names. At each iteration within the loop the all of the names will change at the same time.
For example, this is how I answered the section in code block 2:
for (f in 1:(length(LD139_040))){
currenttile<-LD139_040[f]
Blue<-B139_040[f]
newmatrix<- matrix(0,nrow(Blue),ncol(Blue))
for (g in 1:(ncol(B139_040[f]))){
for (h in 1:(nrow(B139_040[f]{
if (S139_040[g,h]>10 & currenttile[g,h]>.295 & currenttile[g,h]<.33 & Blue [g,h]<180)
{newmatrix[g,h]<-1}
}
}
}
Put even more simply, since I learned that as long as the matrices are the same dimensions, you do not have to loop through each location:
for (f in 1:(length(LD139_040))){
currenttile<-LD139_040[f]
Blue<-B139_040[f]
newmatrix<- matrix(0,nrow(Blue),ncol(Blue))
currenttile[currenttile >.295 & currenttile <.33]<- 1
Blue[Blue<180]<- 1
newmatrix[Blue==1 & currenttile==1]<- 1
}
So thanks to everyone who tried to decipher this, it was a confusing problem for me to it took a while to figure out how to best approach it, (and obviously how to explain it). I hope this helps someone!

Remove item from groovy list

I am trying to remove an item from groovy list. I've tried following:
List<User> availableUsers = []
availableUsers = workers
for (int i = 0; i < availableUsers.size(); i++) {
if (availableUsers[i].equals(user)){
availableUsers.drop(i)
break
}
}
I've also tried:
availableUsers.remove(user)
In both cases the list gets emptied. Does anyone have any idea what's going on?
Have you tried
availableUsers - user
?
Docu: http://groovy.codehaus.org/groovy-jdk/java/util/List.html#minus(java.lang.Object)
Haven't got much experience with groovy myself, but that's what I would try.
As mentioned above, the answer depends on whether you wish to remove all occurrences of an item...
myList = ['a','b','c', 'c']
myList -= 'c'
assert myList == ['a','b']
...or just the first instance.
myList = ['a','b','c', 'c']
myList.remove(myList.indexOf('c'))
assert myList == ['a','b','c']
I'm still new to Groovy myself, but one of the underlying principles is that it almost always has a way of making common tasks trivial one-liners. Adding or removing items from a collection would certainly qualify.
Fildor is right, but if you only want ot remove the first occurence of user in your list (minus will remove all occurrences), you will probably need something like:
list = list.indexOf( user ).with { idx ->
if( idx > -1 ) {
new ArrayList( list ).with { a ->
a.remove( idx )
a
}
}
else list
}
I had a related requirement but wanted to remove more than one items knowing their index position. It was not easy to do in a loop as after removing the first item, the index position of the remaining ones changes. It seemed easy to first create a list with items to be removed and then use the collections minus operation to remove them from the target list. Here is an example:
myList=['a','b','c','d']
remove=[0,1,2] //index list of list elements to remove
removeList=myList[remove]
println removeList
assert ['d']== myList.minus(removeList)
LIMITATION:if the value at index is present multiple times in target list, ALL instances are removed.
So, if
myList=['a','b','c','d','a','e']
remove=[0,1,2]
removeList=myList[remove]
assert myList.minus(removeList)== ['d','e']
the result will be d,e

Resources