HaskellWiki

Haskell | Wiki community | Recent changes
Random page | Special pages

 

Not logged in
Log in | Help

Haskell Quiz/Sampling/Solution Dolio

< Haskell Quiz | Sampling

Categories: Haskell Quiz solutions


This is a somewhat naive algorithm, but it manages to run the challenge problem in a reasonable amount of time. It simply uses the IntSet data structure, testing and adding random numbers until enough are found.

module Main where
import qualified Data.IntSet as I
import System
import System.Random
 
build n k s (r:rs)
    | k `seq` s `seq` False = undefined -- strictness
    | k >= n             = s
    | not $ I.member r s = build n (k+1) (I.insert r s) rs
    | otherwise          = build n k s rs
 
main = do [n, l] <- fmap (map read) getArgs
          g <- getStdGen
          if n > l
           then putStrLn "Your request is impossible."
           else putStr . unlines . map show . I.elems
                       $ build n 0 I.empty (randomRs (0, l-1) g)

A run of the sample problem on my machine took about 1 minute.

Retrieved from "http://www.haskell.org/haskellwiki/Haskell_Quiz/Sampling/Solution_Dolio"

This page has been accessed 588 times. This page was last modified 10:55, 13 January 2007. Recent content is available under a simple permissive license.