-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay05.hs
84 lines (74 loc) · 2.5 KB
/
Day05.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
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
module Day05 where
import Control.Monad (void)
import Text.ParserCombinators.ReadP
import Harness
import ParseHelper
import qualified GHC.Arr as A
main :: IO ()
main =
getInputAndSolve (parseInput parseLine) (findOverlaps lineIsStraight) (findOverlaps $ const True)
where
lineIsStraight Line{..} =
fst lEnd == fst lStart || snd lEnd == snd lStart
findOverlaps :: (Line -> Bool) -> [Line] -> Int
findOverlaps lineFilter (filter lineFilter -> ls) =
let
maxX =
maximum $ concatMap (\Line{..} -> [fst lStart, fst lEnd]) ls
maxY =
maximum $ concatMap (\Line{..} -> [snd lStart, snd lEnd]) ls
emptyGrid =
A.listArray ((0, 0), (maxX, maxY))
$ replicate @Int (succ maxX * succ maxY) 0
filledGrid =
foldr
(\l arr ->
A.accum (+) arr $ zip (toPoints l) $ repeat 1
)
emptyGrid
ls
in A.foldrElems' (\i c -> if i >= 2 then succ c else c) 0 filledGrid
where
toPoints :: Line -> [(Int, Int)]
toPoints Line{..}
| fst lStart == fst lEnd =
[(fst lStart, y) | y <- [snd left .. snd right]]
| snd lStart == snd lEnd =
[(x, snd lStart) | x <- [fst left .. fst right]]
| otherwise =
let xDirection = getDirection fst
yDirection = getDirection snd
in
zip
[fst lStart, fst lStart + xDirection .. fst lEnd]
[snd lStart, snd lStart + yDirection .. snd lEnd]
where
(left, right) =
if lStart < lEnd
then (lStart, lEnd)
else (lEnd, lStart)
getDirection :: ((Int, Int) -> Int) -> Int
getDirection sel =
let diff = (sel lEnd - sel lStart)
in diff `div` abs diff
data Line
= Line
{ lStart :: (Int, Int)
, lEnd :: (Int, Int)
} deriving (Show, Read, Eq, Ord)
parseLine :: ReadP Line
parseLine = do
lStart <- parsePair
void $ string " -> "
lEnd <- parsePair
return Line {..}
where
parsePair :: ReadP (Int, Int)
parsePair = do
x <- parseInt
void $ char ','
y <- parseInt
return (x, y)