-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day7.hs
94 lines (84 loc) · 2.57 KB
/
Day7.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
module Day7
( part1
, part2
) where
import Data.Bifunctor (first, second)
import Data.Either (fromRight)
import Data.List (intersect)
import Data.List.Split (splitOneOf)
import Data.Text as T (Text, lines, unpack)
import Helpers.Parsers.Text (Parser)
import Text.Megaparsec (eof, lookAhead, parse, try, (<|>))
import Text.Megaparsec.Char (char, printChar)
hasTLS :: Text -> Bool
hasTLS =
(\(a, b) -> a && not b) . fromRight (False, True) . parse parseExternalABBA ""
parseExternalABBA :: Parser (Bool, Bool)
parseExternalABBA =
try (printChar >> printChar >> printChar >> eof >> return (False, False))
<|> (do
char '['
parseInternalABBA)
<|> do
a <- printChar
(b, c, d) <-
lookAhead $ do
b <- printChar
c <- printChar
d <- printChar
return (b, c, d)
first ((a == d && b == c && a /= b) ||) <$> parseExternalABBA
parseInternalABBA :: Parser (Bool, Bool)
parseInternalABBA = do
a <- printChar
(b, c, d) <-
lookAhead $ do
b <- printChar
c <- printChar
d <- printChar
return (b, c, d)
if a == ']'
then parseExternalABBA
else second ((a == d && b == c && a /= b) ||) <$> parseInternalABBA
alternate :: a -> ([a], [a]) -> ([a], [a])
alternate x (others, ones) = (x : ones, others)
hasSSL :: Text -> Bool
hasSSL =
not
. null
. uncurry intersect
. fromRight ([], [])
. parse parseExternalABA ""
parseExternalABA :: Parser ([(Char, Char)], [(Char, Char)])
parseExternalABA =
try (printChar >> printChar >> eof >> return ([], []))
<|> (do
char '['
parseInternalBAB)
<|> do
a <- printChar
(b, c) <-
lookAhead $ do
b <- printChar
c <- printChar
return (b, c)
if a == c && a /= b
then first ((a, b) :) <$> parseExternalABA
else parseExternalABA
parseInternalBAB :: Parser ([(Char, Char)], [(Char, Char)])
parseInternalBAB = do
a <- printChar
(b, c) <-
lookAhead $ do
b <- printChar
c <- printChar
return (b, c)
let result
| a == ']' = parseExternalABA
| a == c && a /= b = second ((b, a) :) <$> parseInternalBAB
| otherwise = parseInternalBAB
result
part1 :: Bool -> Text -> String
part1 _ = show . length . filter hasTLS . T.lines
part2 :: Bool -> Text -> String
part2 _ = show . length . filter hasSSL . T.lines