Commit 9372a0be authored by Nicolas Lenz's avatar Nicolas Lenz

Day05 yay

parent af273282
......@@ -4,7 +4,7 @@ cabal-version: 1.12
--
-- see: https://github.com/sol/hpack
--
-- hash: a31d69558fb7c391bf70ef12c046d4b4a10a2fd42e24f572cc4592799a825b1b
-- hash: 7f535108a3ad03db9bb5b3d1976f1e0422bbe0eddd7da2483c1581fa3dd7c089
name: advent-of-code
version: 0.0.0
......@@ -31,6 +31,7 @@ executable advent-of-code
Day02
Day03
Day04
Day05
Paths_advent_of_code
hs-source-dirs:
src
......
This diff is collapsed.
module Day05 (part1, part2) where
import Data.Char
-- Reduces the input and returns the length.
part1 :: [String] -> String
part1 [input] = show $ length $ reduce input
-- Reduces the input once with every character removed and returns the length of the shortest reduct.
part2 :: [String] -> String
part2 [input] = show $ minBySnd $ liftSnd length <$> liftSnd reduce <$> listRemoves input
example :: [String]
example = ["dabAcCaCBAcCcaDA"]
-- Reduces a list of characters recursively.
reduce :: [Char] -> [Char]
reduce [] = []
reduce (c:cs) = case reduce cs of
(d:ds) | c `react` d -> ds
| otherwise -> (c:d:ds)
[] -> [c]
-- Checks whether two units can react, i.e. are the same character in different cases.
react :: Char -> Char -> Bool
react c1 c2 = c1 /= c2 && toLower c1 == toLower c2
-- Returns a list which contains a pair for each character from 'a' to 'z' with the character and the given string with all occurences (ignoring case) of that character removed.
listRemoves :: String -> [(Char, String)]
listRemoves str = [(c, filter ((/=c) . toLower) str) | c <- ['a'..'z']]
-- Lifts a function to a function working on the second component of a pair.
liftSnd :: (a -> b) -> (c,a) -> (c,b)
liftSnd f (c,a) = (c, f a)
-- Gets the pair with the minimal value in the second component from a list.
minBySnd :: (Ord b) => [(a,b)] -> (a,b)
minBySnd [(a,b)] = (a,b)
minBySnd ((a,b):ls)
| snd (minBySnd ls) < b = minBySnd ls
| otherwise = (a,b)
......@@ -3,6 +3,7 @@ import Day01
import Day02
import Day03
import Day04
import Day05
solutions :: [((String, String), [String] -> String)]
......@@ -14,7 +15,9 @@ solutions = [
(("03", "1"), Day03.part1),
(("03", "2"), Day03.part2),
(("04", "1"), Day04.part1),
(("04", "2"), Day04.part2)]
(("04", "2"), Day04.part2),
(("05", "1"), Day05.part1),
(("05", "2"), Day05.part2)]
main :: IO ()
main = do
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment