2019-12-03 07:49:10 +01:00
import Data.List.Split
import Data.List
import qualified Data.Set as Set
import Data.Maybe
2019-12-03 15:50:55 +01:00
import Linear.V2
2019-12-03 07:49:10 +01:00
main = do
content <- readFile " input "
2019-12-03 15:50:55 +01:00
let [ trace1 , trace2 ] = map gensteps $ parse content
2019-12-03 07:49:10 +01:00
print ( day3a trace1 trace2 )
print ( day3b trace1 trace2 )
2019-12-03 15:50:55 +01:00
parse :: String -> [ [ ( Char , Int ) ] ]
parse = map ( map ( \ x -> ( head x , read $ tail x ) ) ) . map ( splitOn " , " ) . lines
2019-12-03 07:49:10 +01:00
2019-12-03 15:50:55 +01:00
gensteps :: [ ( Char , Int ) ] -> [ V2 Int ]
2019-12-03 16:10:48 +01:00
gensteps = scanl1 ( + ) . concatMap ( \ ( x , y ) -> replicate y $ step x )
2019-12-03 07:49:10 +01:00
2019-12-03 15:50:55 +01:00
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
2019-12-03 07:49:10 +01:00
2019-12-03 15:50:55 +01:00
day3a :: [ V2 Int ] -> [ V2 Int ] -> Int
2019-12-03 07:49:10 +01:00
day3a xs ys = Set . findMin $ Set . map manhattan ( intersections xs ys )
2019-12-03 15:50:55 +01:00
where manhattan ( V2 x y ) = abs x + abs y
2019-12-03 07:49:10 +01:00
2019-12-03 15:50:55 +01:00
intersections :: [ V2 Int ] -> [ V2 Int ] -> Set . Set ( V2 Int )
2019-12-04 00:43:18 +01:00
intersections xs ys = ( Set . fromList xs ) ` Set . intersection ` ( Set . fromList ys )
2019-12-03 07:49:10 +01:00
2019-12-04 00:43:18 +01:00
day3b xs ys = minimum [ let f = succ . fromJust . elemIndex x in
2019-12-03 15:50:55 +01:00
f xs + f ys | x <- Set . toList $ intersections xs ys ]