X-Git-Url: https://git.njae.me.uk/?a=blobdiff_plain;f=advent06.hs;h=0d32e4cdd89d8a7b81d70a5dcf3df0c0b8dda4e1;hb=43207f4732674c96772536c32c4ed051de7848f6;hp=77d40934c1d83388f9558c37d7948f5f7c766d13;hpb=5bc8c68da5691e57648112363a1df1eda7f0fe3a;p=advent-of-code-16.git

diff --git a/advent06.hs b/advent06.hs
index 77d4093..0d32e4c 100644
--- a/advent06.hs
+++ b/advent06.hs
@@ -1,7 +1,10 @@
+-- Better version of advent06.hs, using more standard library functions.
+
 module Main(main) where
 
-import Data.List (transpose)
+import Data.List (transpose, maximum, minimum)
 import Data.Char (isLetter)
+import Data.Tuple (swap)
 import qualified Data.Map.Lazy as Map
 
 main :: IO ()
@@ -13,24 +16,17 @@ main = do
 
 part1 :: [String] -> IO ()
 part1 message = do 
-    print $ map (fst) $ map (mostCommon) $ map (countedLetters) $ transpose message
+    putStrLn $ map (fst) $ map (mostCommon) $ map (countedLetters) $ transpose message
 
 part2 :: [String] -> IO ()
 part2 message = do 
-    print $ map (fst) $ map (leastCommon) $ map (countedLetters) $ transpose message
-
-
-countedLetters :: String -> Map.Map Char Int
-countedLetters name = Map.fromListWith (+) [(c, 1) | c <- filter (isLetter) name]
-
-mostCommon = Map.foldlWithKey (mostCommonP) ('a', 0)
+    putStrLn $ map (fst) $ map (leastCommon) $ map (countedLetters) $ transpose message
 
-mostCommonP (letter0, count0) letter count
-    | count > count0 = (letter, count)
-    | otherwise = (letter0, count0)
+countedLetters :: String -> [(Char, Int)]
+countedLetters name = Map.toList $ Map.fromListWith (+) [(c, 1) | c <- filter (isLetter) name]
 
-leastCommon = Map.foldlWithKey (leastCommonP) ('a', maxBound :: Int)
+mostCommon :: [(Char, Int)] -> (Char, Int)
+mostCommon = swap . maximum . map (swap)
 
-leastCommonP (letter0, count0) letter count
-    | count < count0 = (letter, count)
-    | otherwise = (letter0, count0)
\ No newline at end of file
+leastCommon :: [(Char, Int)] -> (Char, Int)
+leastCommon = swap . minimum . map (swap)