AoC/2019/day3/day3.hs
shu e64af48b80 Fix solution
6ef036e2c5a actually made the solution incorrect, the list comprehension
for part b relied on V 0 0 being in the list for the element to match
    the step number. The magic oneliner is rad tho so simply adjust the
    list comprehension.
2019-12-04 00:43:18 +01:00

35 lines
1015 B
Haskell

import Data.List.Split
import Data.List
import qualified Data.Set as Set
import Data.Maybe
import Linear.V2
main = do
content <- readFile "input"
let [trace1, trace2] = map gensteps $ parse content
print (day3a trace1 trace2)
print (day3b trace1 trace2)
parse :: String -> [[(Char,Int)]]
parse = map (map (\x->(head x,read $ tail x))) . map (splitOn ",") . lines
gensteps :: [(Char,Int)] -> [V2 Int]
gensteps = scanl1 (+) . concatMap (\(x,y)->replicate y $ step x)
step :: Char -> V2 Int
step x
| x=='U'=V2 0 1
| x=='R'=V2 1 0
| x=='D'=V2 0 (-1)
| x=='L'=V2 (-1) 0
day3a :: [V2 Int] -> [V2 Int] -> Int
day3a xs ys = Set.findMin $ Set.map manhattan (intersections xs ys)
where manhattan (V2 x y) = abs x + abs y
intersections :: [V2 Int] -> [V2 Int] -> Set.Set (V2 Int)
intersections xs ys = (Set.fromList xs) `Set.intersection` (Set.fromList ys)
day3b xs ys = minimum [let f = succ . fromJust . elemIndex x in
f xs + f ys | x<-Set.toList $ intersections xs ys]