andy0130tw
5/9/2018 - 7:29 PM

FLOLAC 2018 Warm-up Week 2 -- histogram: make a histogram from a list of [0..9]

FLOLAC 2018 Warm-up Week 2 -- histogram: make a histogram from a list of [0..9]

numOccs :: [Int] -> [Int]
numOccs xs = map (\n -> length $ filter (== n) xs) [0..9]

histogramLine :: [Int] -> Int -> String
histogramLine freqs bl = map (putc . (>= bl)) freqs
    where putc cond = if cond then '*' else ' '

histogram :: [Int] -> String
histogram xs = unlines $
                 (map (histogramLine freqs) (cbTo1 $ maximum freqs)
                    ++ footer)
    where labels = "0123456789"
          footer = [replicate (length labels) '=', labels]
          freqs = numOccs xs
          cbTo1 x = reverse [1 .. x]

{-
usage: putStr $ histogram [...]

example:
> histogram [1,4,5,4,6,6,3,4,2,4,9]

    *
    *
    * *
 ******  *
==========
0123456789

-}