Browse Source

Day05 yay

master
Nicolas Lenz 9 months ago
parent
commit
9372a0bec1
4 changed files with 49 additions and 1 deletions
  1. 2
    0
      advent-of-code.cabal
  2. 1
    0
      input/day05
  3. 42
    0
      src/Day05.hs
  4. 4
    1
      src/Main.hs

+ 2
- 0
advent-of-code.cabal View File

@@ -4,7 +4,7 @@ cabal-version: 1.12
--
-- see: https://github.com/sol/hpack
--
-- 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

+ 1
- 0
input/day05
File diff suppressed because it is too large
View File


+ 42
- 0
src/Day05.hs View File

@@ -0,0 +1,42 @@
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)

+ 4
- 1
src/Main.hs View File

@@ -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

Loading…
Cancel
Save