Skip to content

Instantly share code, notes, and snippets.

@yuliaju
Created October 18, 2016 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yuliaju/4fc6e8c91bc88ea2c34b8c1e865eda7e to your computer and use it in GitHub Desktop.
Save yuliaju/4fc6e8c91bc88ea2c34b8c1e865eda7e to your computer and use it in GitHub Desktop.
import Text.Printf
import Control.Exception
import System.CPUTime
time :: IO t -> IO t
time a = do
start <- getCPUTime
v <- a
end <- getCPUTime
let diff = (fromIntegral (end - start)) / (10^12)
printf "Computation time: %0.3f sec\n" (diff :: Double)
return v
main = do
putStrLn "Starting..."
time $ memoized_countUniqueBSTs 5 `seq` return ()
putStrLn "Done."
memoized_countUniqueBSTs :: Int -> Integer
memoized_countUniqueBSTs n = (map countUniqueBSTs [0..]) !! n
where countUniqueBSTs 0 = 1
countUniqueBSTs 1 = 1
countUniqueBSTs n = sum $ zipWith (*) (computedBSTs n) (reverse $ computedBSTs n)
computedBSTs n = map memoized_countUniqueBSTs [0..(n-1)]
-- countUniqueBSTs :: Int -> Int
-- countUniqueBSTs 0 = 1
-- countUniqueBSTs 1 = 1
-- countUniqueBSTs n = sum $ zipWith (*) computedBSTS (reverse computedBSTS)
-- where computedBSTS = map countUniqueBSTS [0..(n-1)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment