-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay20.hs
64 lines (53 loc) · 1.45 KB
/
Day20.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
module Day20
( part1
, part2
) where
import Data.Either (fromRight)
import Data.List (sort)
import Data.Text (Text)
import Helpers.Parsers.Text (Parser)
import Text.Megaparsec (eof, manyTill, parse)
import Text.Megaparsec.Char (char, eol)
import Text.Megaparsec.Char.Lexer (decimal)
data Range =
Range Low High
deriving (Show, Eq)
instance Ord Range where
compare (Range a b) (Range c d) = compare a c `mappend` compare b d
type Low = Int
type High = Int
parseInput :: Parser [Range]
parseInput = manyTill parseRange eof
parseRange :: Parser Range
parseRange = do
a <- decimal
char '-'
b <- decimal
eol
return $ Range a b
merge :: Range -> [Range] -> [Range]
merge x [] = [x]
merge r1@(Range a b) rest@(r2@(Range c d):rest')
| c > b + 1 = r1 : rest
| b >= d = merge r1 rest'
| otherwise = merge (Range a d) rest'
findFree :: [Range] -> Int
findFree [x] = 0
findFree (Range _ a:rest@(Range b _:_)) = b - a - 1 + findFree rest
part1 :: Bool -> Text -> String
part1 _ =
show
. (\(Range _ b) -> b + 1)
. head
. foldr merge []
. sort
. fromRight (error "parse failed")
. parse parseInput "day20"
part2 :: Bool -> Text -> String
part2 _ =
show
. findFree
. foldr merge []
. sort
. fromRight (error "parsefailed")
. parse parseInput "20"