tangled
alpha
login
or
join now
eldridge.cam
/
advent-of-code
2
fork
atom
Advent of Code solutions
2
fork
atom
overview
issues
pulls
pipelines
2021:14
eldridge.cam
1 year ago
e8ef06e1
f87886e6
+70
2 changed files
expand all
collapse all
unified
split
2021
14
p1.hs
p2.hs
+35
2021/14/p1.hs
···
1
1
+
import Control.Arrow
2
2
+
import Text.Parsec
3
3
+
import Data.List
4
4
+
import Data.Map qualified as Map
5
5
+
6
6
+
initialize ps = Map.unionsWith (+) $ fmap (flip Map.singleton 1) $ ps `zip` tail ps
7
7
+
8
8
+
rule = do
9
9
+
a:b:_ <- count 2 letter
10
10
+
string " -> "
11
11
+
to <- letter
12
12
+
return $ Map.singleton (a, b) [(a, to), (to, b)]
13
13
+
14
14
+
input = do
15
15
+
initial <- many letter
16
16
+
count 2 newline
17
17
+
rules <- rule `endBy` newline
18
18
+
return (initial, Map.unions rules)
19
19
+
20
20
+
step rules state = Map.unionsWith (+) $ do
21
21
+
(k, v) <- Map.assocs state
22
22
+
k2 <- rules Map.! k
23
23
+
return $ Map.singleton k2 v
24
24
+
25
25
+
answer contents =
26
26
+
uncurry (-)
27
27
+
$ maximum &&& minimum
28
28
+
$ Map.unionWith (+) (Map.singleton (last initial) 1)
29
29
+
$ Map.mapKeysWith (+) fst
30
30
+
$ (!! 10)
31
31
+
$ iterate (step rules)
32
32
+
$ initialize initial
33
33
+
where Right (initial, rules) = parse input "" contents
34
34
+
35
35
+
main = getContents >>= print . answer
+35
2021/14/p2.hs
···
1
1
+
import Control.Arrow
2
2
+
import Text.Parsec
3
3
+
import Data.List
4
4
+
import Data.Map qualified as Map
5
5
+
6
6
+
initialize ps = Map.unionsWith (+) $ fmap (flip Map.singleton 1) $ ps `zip` tail ps
7
7
+
8
8
+
rule = do
9
9
+
a:b:_ <- count 2 letter
10
10
+
string " -> "
11
11
+
to <- letter
12
12
+
return $ Map.singleton (a, b) [(a, to), (to, b)]
13
13
+
14
14
+
input = do
15
15
+
initial <- many letter
16
16
+
count 2 newline
17
17
+
rules <- rule `endBy` newline
18
18
+
return (initial, Map.unions rules)
19
19
+
20
20
+
step rules state = Map.unionsWith (+) $ do
21
21
+
(k, v) <- Map.assocs state
22
22
+
k2 <- rules Map.! k
23
23
+
return $ Map.singleton k2 v
24
24
+
25
25
+
answer contents =
26
26
+
uncurry (-)
27
27
+
$ maximum &&& minimum
28
28
+
$ Map.unionWith (+) (Map.singleton (last initial) 1)
29
29
+
$ Map.mapKeysWith (+) fst
30
30
+
$ (!! 40)
31
31
+
$ iterate (step rules)
32
32
+
$ initialize initial
33
33
+
where Right (initial, rules) = parse input "" contents
34
34
+
35
35
+
main = getContents >>= print . answer