import Data.List (sort, group, maximumBy) {- To run this code in terminal: - runghc skurla_kamil_du4_histogram.hs -} values :: [Int] values = [6,2,12,10,7,3,0,12,4,8,7,8,10,13,10,8,2,11,17,9,16,12,14,9,9,2,7,3,7,10,1,11,11,13,10,12,15,9,15,13,9,8,16,1,18,9,10,13,15,5,13,15,11,10,8,1,9,13,10,9,7,14,6,6,9,14,12,17,7,7,4,12,11,4,7,8,10,6,14,6,13,14,4,1,10,1,8,11] histogram :: [Int] -> String histogram numbers = unlines (legendC `sideBySide` (drawRows height occ `stacked` [legendL])) where occ = allOccurrences numbers height = snd (mostFrequent occ) legendL = legendLine occ legendC = legendColumn height countOccurrences :: Ord a => [a] -> [(a, Int)] countOccurrences xs = map (\g -> (head g, length g)) (group (sort xs)) mostFrequent :: Ord b => [(a, b)] -> (a, b) mostFrequent = maximumBy (\a b -> compare (snd a) (snd b)) allOccurrences :: [Int] -> [(Int, Int)] allOccurrences xs = [(n, maybe 0 id (lookup n occ)) | n <- [0 .. maximum xs]] where occ = countOccurrences xs drawRow :: Int -> [(Int, Int)] -> String drawRow target occ = concatMap cell occ where cell (_, c) = if c >= target then " |" else " " drawRows :: Int -> [(Int, Int)] -> [String] drawRows 0 _ = [] drawRows target occ = drawRow target occ : drawRows (target - 1) occ legendCell :: Int -> String legendCell target | target `mod` 5 == 0 = alignRight 2 (show target) | otherwise = " " legendLine :: [(Int, Int)] -> String legendLine occ = concatMap (legendCell . fst) occ legendColumn :: Int -> [String] legendColumn height = map legendCell (reverse [1..height]) ++ [" "] alignRight :: Int -> String -> String alignRight width str = replicate (width - length str) ' ' ++ str sideBySide :: [String] -> [String] -> [String] sideBySide left right = zipWith (++) left right stacked :: [String] -> [String] -> [String] stacked top bottom = top ++ bottom ---------------------------------------------- -- main main :: IO () main = do putStrLn "---- histogram ----" putStr (histogram values)