-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay2.hs
97 lines (77 loc) · 2.17 KB
/
Day2.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
module Day2 where
import Control.Applicative ((<|>))
import Data.Functor (($>))
import Data.Map (Map)
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Tuple (swap)
import Parser
import Utils (groupOn)
import Witherable (mapMaybe)
program :: FilePath -> IO ()
program = (=<<) print . fmap logic . T.readFile
data Answer = Answer Int Int deriving (Eq, Show)
logic :: T.Text -> Answer
logic = (Answer <$> part1 <*> part2) . parseGames
bag :: Bag
bag =
Bag
$ M.fromList
[ (Red, 12)
, (Green, 13)
, (Blue, 14)
]
part1 :: [Game] -> Int
part1 =
getSum
. foldMap (Sum . gameId)
. filter (isGamePossible bag)
part2 :: [Game] -> Int
part2 =
getSum
. foldMap (Sum . power)
data Colour = Blue | Green | Red deriving (Eq, Show, Bounded, Enum, Ord)
newtype Bag = Bag (Map Colour Int) deriving (Eq, Show)
newtype Sample = Sample {draws :: [(Colour, Int)]} deriving (Eq, Show)
data Game = Game
{ gameId :: Int
, samples :: [Sample]
}
deriving (Eq, Show)
power :: Game -> Int
power =
getProduct
. foldMap Product
. M.elems
. fmap (maximum . fmap snd)
. groupOn fst
. (=<<) draws
. samples
isCubePossible :: Bag -> (Colour, Int) -> Bool
isCubePossible (Bag m) (colour, n) =
let
maxAvailable = fromMaybe 0 (M.lookup colour m)
in
n <= maxAvailable
isSamplePossible :: Bag -> Sample -> Bool
isSamplePossible b (Sample cubes) = all (isCubePossible b) cubes
isGamePossible :: Bag -> Game -> Bool
isGamePossible b (Game _ s) = all (isSamplePossible b) s
colourP :: Parser Colour
colourP = string "blue" $> Blue <|> string "red" $> Red <|> string "green" $> Green
gameIdP :: Parser Int
gameIdP = string "Game " *> decimal <* string ":"
sampleP :: Parser Sample
sampleP = Sample <$> pairP `sepBy` char ','
where
pairP :: Parser (Colour, Int)
pairP = swap <$> ((,) <$> (space *> decimal <* space) <*> colourP)
samplesP :: Parser [Sample]
samplesP = sampleP `sepBy` char ';'
gameP :: Parser Game
gameP = Game <$> gameIdP <*> samplesP
parseGames :: T.Text -> [Game]
parseGames = mapMaybe (parseAll gameP . T.unpack) . T.lines