Skip to content

Instantly share code, notes, and snippets.

@vankesteren
Last active April 18, 2018 21:14
Show Gist options
  • Select an option

  • Save vankesteren/69ded86c3747c53f3b9da6b910fb2db9 to your computer and use it in GitHub Desktop.

Select an option

Save vankesteren/69ded86c3747c53f3b9da6b910fb2db9 to your computer and use it in GitHub Desktop.
A few recursive R algorithms
# Sequences
# sequence of integers
int=function(s,e)if(s<=e)c(s,int(s+1,e))
int(2, 12)
# nth fibonacci number
fib=function(n)ifelse(n<=1,1,fib(n-1)+fib(n-2))
fib(0:10)
# Mathy stuff
# greatest common divisor (euclid's algorithm)
gcd=function(a,b)ifelse(b==0,a,gcd(b,a%%b))
gcd(1232,88)
# multiplication with only + and - (always put largest first)
mtp=function(a,b)ifelse(b==0,0,b+mtp(b,a-1))
mtp(21,4.5)
# factorial with only + and -
fac=function(x)ifelse(x==2,2,mtp(fac(x-1),x))
fac(7)
# power with only + and -
pow=function(x,n)ifelse(n<=0,1,mtp(pow(x,n-1),x))
pow(3,3)
# actually sometimes useful stuff
# get the elements of a nested list with a certain name
gli=function(l,n){i=names(l)==n
c(l[i],unlist(lapply(l[!i],function(sl)if(is.list(sl))gli(sl,n)),r=F))}
nl <- list(a = 1, b = list(a = 2, c = list(d = 1, e = list(f = 1), g = list(a = 3))))
gli(nl, "a")
# find the nth lowest number of a vector
flo=function(v,n){l=h=c();for(e in v[-1])ifelse(e<v[1],l<-c(l,e),h<-c(e,h))
ll=length(l);ifelse(n<=ll,return(flo(l,n)),ifelse(n>=ll+2,flo(h,n-1-ll),v[1]))}
flo(rnorm(101),51)
@vankesteren

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment