Skip to content

Instantly share code, notes, and snippets.

@erantapaa
Created December 15, 2014 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erantapaa/69fa2c060f67d74e477a to your computer and use it in GitHub Desktop.
Save erantapaa/69fa2c060f67d74e477a to your computer and use it in GitHub Desktop.
Timing subsequencesOfSize
import System.TimeIt
import System.Environment
import Text.Printf
subsequencesOfSize1 :: Int -> [a] -> [[a]]
subsequencesOfSize1 n xs = let l = length xs
in if n>l then [] else subsequencesBySize xs !! (l-n)
where
subsequencesBySize [] = [[[]]]
subsequencesBySize (x:xs) = let next = subsequencesBySize xs
in zipWith (++) ([]:next) (map (map (x:)) next ++ [[]])
-- this one is faster
subsequencesOfSize2 :: Int -> [a] -> [[a]]
subsequencesOfSize2 n xs | n > length xs = []
subsequencesOfSize2 n xs = subsequencesBySize xs !! n where
subsequencesBySize [] = [[[]]]
subsequencesBySize (x:xs) = zipWith (++) ([] : map (map (x:)) next) (next ++ [[]])
where next = subsequencesBySize xs
-- e.g. k = 3, n = 150
main = do
(ks:ns:_) <- getArgs
let k = read ks
n = read ns :: Int
time e = timeItT $ seq e (return e)
print ("k, n:", k, n)
(t2,r2) <- time $ length $ subsequencesOfSize2 k [1..n]
putStrLn $ printf "version 2, time: %7.3f, result: %d" t2 r2
(t1,r1) <- time $ length $ subsequencesOfSize1 k [1..n]
putStrLn $ printf "version 1, time: %7.3f, result: %d" t1 r1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment