the Catalan numbers: recursive formula for # binary trees, # triangulations of a polygon, and more
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
catalan :: (Integral n) => n -> n -- not memoised | |
catalan 0 = 1 | |
catalan n = sum [ catalan i * catalan(n-1-i) | i <- [0..n-1] ] --N:=n+1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
catalan <- function(N) { | |
if (N==0) 1 | |
else | |
n=N-1 #power of notation | |
#not memoised | |
lapply(0:n, FUN=function(i) catalan(i) * catalan(n-i) ) %>% unlist %>% sum | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
catalan <- function(n) { | |
#make a memo | |
if (!exists('cat.save') || length(cat.save) < n) { cat.save <<- integer(n) } | |
#actual catalan function | |
#base layer | |
if (n==0) 1 | |
#recursive part | |
else { | |
#reuse | |
if (cat.save[n] !=0) { cat.save[n] } | |
else | |
#Catalan formula | |
(cat.save[n] <<- lapply(0:n, FUN=function(i) catalan(i-1) * catalan(n-i) ) %>% unlist %>% sum) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment