Skip to content

Commit 41fe606

Browse files
committed
Improve day 5 solution to O(n * log n) from O(n ^ 2)
sort and group are neat :)
1 parent c51433c commit 41fe606

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

2021/5/better.hs

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import Data.List (group, sort)
2+
import qualified Data.Text as Text
3+
import qualified Data.Text.IO as Text
4+
import qualified Data.Set as Set
5+
import Control.Monad
6+
7+
readInput f = Text.readFile f
8+
>>= let parsePoint = map . Text.splitOn
9+
splitLine t = let (l, r) = Text.break (== ',') $ t
10+
(x, _:y) = (Text.unpack l, Text.unpack r)
11+
in (read x, read y)
12+
in return . (map $ map splitLine)
13+
. (map $ Text.splitOn $ Text.pack " -> ")
14+
. Text.lines
15+
16+
points d [(x, y), (x', y')] = let b a b' = [a, a + signum (b' - a) .. b']
17+
in if x == x' || y == y'
18+
then if x == x'
19+
then zip (repeat x) (b y y')
20+
else zip (b x x') (repeat y)
21+
else if d && abs (x - x') == abs (y - y')
22+
then zip (b x x') (b y y')
23+
else []
24+
25+
count' = length . filter (> 1) . map length . group . sort
26+
27+
part12 d f = (readInput f :: IO [[(Int, Int)]])
28+
>>= return . count' . concat . map (points d)
29+
30+
main = (part12 False "input.txt" >>= print)
31+
>> (part12 True "input.txt" >>= print)

0 commit comments

Comments
 (0)