-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.hs
66 lines (52 loc) · 1.48 KB
/
run.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeApplications #-}
import Data.List (intersect, stripPrefix)
import Data.List.Split
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
type N = Int
nums :: String -> [N]
nums = map (read @N) . words
parse :: String -> Card
parse input =
let [cs, numbers] = splitOn ": " input
[winnings, yours] = splitOn " | " numbers
Just idx = dropWhile (== ' ') <$> "Card" `stripPrefix` cs
in
(read idx, (nums winnings, nums yours))
type Card = (Int, ([N], [N]))
parseAll :: String -> [Card]
parseAll = map parse . lines
wins :: ([N], [N]) -> Int
wins (w, draw) =
length $ w `intersect` draw
score :: Card -> N
score (_, c) =
case wins c of
0 -> 0
n -> 2 ^ (n - 1)
part1 :: [Card] -> N
part1 =
sum . map score
ones :: [N] -> HashMap N Int
ones = HashMap.fromList . map (, 1)
part2 :: [Card] -> Int
part2 cs = sum $ go (ones $ map fst cs) cs
where go counts = \case
[] -> counts
(i, c):rest ->
let w = wins c
Just n = counts HashMap.!? i
winners = HashMap.map (*n) . ones $ map (+i) [1..w]
counts' = HashMap.unionWith (+) counts winners
in go counts' rest
main :: IO ()
main = main' "input.txt"
exampleMain :: IO ()
exampleMain = main' "example.txt"
main' :: FilePath -> IO ()
main' file = do
input <- parseAll <$> readFile file
print (part1 input)
print (part2 input)