Hi I am trying to convert the following recursive pseudocode definition into a functional programming construct in R :
a = [ random numbers between 0 and 10 ]
b = [ random numbers between -5 and 5 ]
c = [ random numbers between 0 and -10 ]
x0 = 200
index = 0
function f(x) {
index = index + 1
if( x is between 200 and 220 ) return f(x + a[index])
else if(x is between 220 and 250) return f(x + b[index])
else if(x is 250 and above) return f(x + c[index])
}
Executable R code is :
a <- sample(1:10,size=50, replace=TRUE)
b <- sample(-5:5,size=50, replace=TRUE)
c <- sample(-1:-10,size=50, replace=TRUE)
index <- 0;
myfunc <- function(x){
index <<- index + 1;
if(index == 50) return(x)
if(x <= 220){ return(myfunc(x + a[index])) }
else if(x > 220 & x < 250){ return(myfunc(x + b[index])) }
else {return( myfunc(x + c[index]))}
}
print(myfunc(200));
Would like to discuss any approach including Map/Filter/Reduce or Vectorisation. Many thanks in advance.
Furthermore, how can I retain the entire path of 50 x elements (rather than looking at just the one answer of x).
You can use the Reduce function with the accumulate option to save all the intermediate values.
To see how this works, try it out on the simple "sum" function
x = rep(200, 50)
Reduce(x=x, f=sum)
Reduce(x=x, f=sum, accumulate=T)
The answer you're looking for requires you rewrite your special function so it can be passed to Reduce:
foo <- function(x, y = 0){
if (200 <= x & x < 220){
x + sample(1:10, 1)
}
else if(220 <= x & x < 250){
x + sample(-5:5, 1)
}
else if (250 <= x){
x + sample(-1:-10, 1)
}
}
Reduce(x=rep(200, 50), f=foo, accumulate=T)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With