mirror of
https://codeberg.org/JasterV/aoc2024-haskell.git
synced 2026-04-26 18:10:05 +00:00
feat: finish day 5
This commit is contained in:
parent
76db862cb0
commit
63cba3eba2
2 changed files with 19 additions and 6 deletions
19
src/Day5.hs
19
src/Day5.hs
|
|
@ -17,13 +17,22 @@ partOne :: String -> Either ParseError Int
|
|||
partOne input = do
|
||||
(rules, updates) <- parseInput input
|
||||
return $ sum $ map middleElem $ filter (isValidUpdate rules) updates
|
||||
where
|
||||
isValidUpdate rules update = sortBy (compareByRules rules) update == update
|
||||
compareByRules rules x y = if member (x, y) rules then LT else GT
|
||||
middleElem update = update !! (length update `div` 2)
|
||||
|
||||
partTwo :: String -> Either ParseError Int
|
||||
partTwo _ = Right 0
|
||||
partTwo input = do
|
||||
(rules, updates) <- parseInput input
|
||||
return $ sum $ map (middleElem . sortUpdate rules) $ filter (not . isValidUpdate rules) updates
|
||||
|
||||
isValidUpdate :: Set Rule -> Update -> Bool
|
||||
isValidUpdate rules update = sortUpdate rules update == update
|
||||
|
||||
sortUpdate :: Set Rule -> Update -> Update
|
||||
sortUpdate rules = sortBy compareByRules
|
||||
where
|
||||
compareByRules x y = if member (x, y) rules then LT else GT
|
||||
|
||||
middleElem :: Update -> Int
|
||||
middleElem update = update !! (length update `div` 2)
|
||||
|
||||
parseInput :: String -> Either ParseError (Set Rule, [Update])
|
||||
parseInput content = case T.splitOn separator text of
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
module Day5Spec (spec) where
|
||||
|
||||
import Day5 (partOne)
|
||||
import Day5 (partOne, partTwo)
|
||||
import Test.Hspec
|
||||
|
||||
spec :: Spec
|
||||
|
|
@ -8,6 +8,10 @@ spec = do
|
|||
describe "PartOne" $ do
|
||||
it "works" $ do
|
||||
partOne input `shouldBe` Right 143
|
||||
|
||||
describe "PartTwo" $ do
|
||||
it "works" $ do
|
||||
partTwo input `shouldBe` Right 123
|
||||
where
|
||||
input =
|
||||
"47|53\n\
|
||||
|
|
|
|||
Loading…
Reference in a new issue