adventofcode-2020/day6/main.hs
2020-12-07 20:32:40 +02:00

72 lines
1.7 KiB
Haskell
Executable file

#! /usr/bin/env -S"ANSWER=42" nix-shell
#! nix-shell -p ghcid
#! nix-shell -p "haskellPackages.ghcWithPackages (p: with p; [shower])"
#! nix-shell -i "ghcid -c 'ghci -Wall' -T main"
{-# LANGUAGE OverloadedStrings #-}
-- import Debug.Trace (trace)
import Data.List (nub)
exampleData :: [String]
exampleData =
[ "abc"
, ""
, "a"
, "b"
, "c"
, ""
, "ab"
, "ac"
, ""
, "a"
, "a"
, "a"
, "a"
, ""
, "b"
]
-- Count how many different chars per paragraph and sum them
countUniqueAnswers :: [String] -> Int
countUniqueAnswers = length . nub . concat
paragraphs :: [String] -> [[String]]
paragraphs strs = go (strs, [])
where
go :: ([String], [[String]]) -> [[String]]
go ([], ys) = ys
go (x:xs, []) = go (xs, [x] : [])
go ("":xs, ys) = go (xs, [] : ys)
go (x:xs, y:ys) = go (xs, (x:y) : ys)
solvePart1 :: [String] -> Int
solvePart1 = sum . (map countUniqueAnswers) . paragraphs
allAnsweredX :: Char -> [[String]] -> [Bool]
allAnsweredX c = map (all (any (== c)))
solvePart2 :: [String] -> Int
solvePart2 strs = length . (filter (== True)) $ concat $ map (\x -> (allAnsweredX x . paragraphs) strs) ['a'..'z']
main :: IO ()
main = do
putStrLn "Day 6 - Part 1"
print $ exampleData
print $ countUniqueAnswers [""]
print $ countUniqueAnswers ["abc"]
print $ countUniqueAnswers ["a", "b", "c"]
print $ countUniqueAnswers ["ab", "ac"]
putStrLn "Day 6 - Part 1 : solving test"
print $ solvePart1 exampleData
putStrLn "Day 6 - Part 1 : solving input"
input <- lines <$> readFile "day6/input"
print $ solvePart1 input
putStrLn "Day 6 - Part 2 : solving test"
print $ paragraphs exampleData
print $ solvePart2 exampleData
putStrLn "Day 6 - Part 2 : solving input"
print $ solvePart2 input