day 3: Improve the solution a bit
This commit is contained in:
parent
3ffa8fac0f
commit
0e03545e94
|
@ -2,35 +2,34 @@ import Data.List.Split
|
||||||
import Data.List
|
import Data.List
|
||||||
import qualified Data.Set as Set
|
import qualified Data.Set as Set
|
||||||
import Data.Maybe
|
import Data.Maybe
|
||||||
|
import Linear.V2
|
||||||
|
|
||||||
main = do
|
main = do
|
||||||
content <- readFile "input"
|
content <- readFile "input"
|
||||||
let input = map (splitOn ",") (lines content)
|
let [trace1, trace2] = map gensteps $ parse content
|
||||||
let parsedinput = map (map parseone) input
|
|
||||||
let trace1 = tracewire (head parsedinput) (0,0) [(0,0)]
|
|
||||||
let trace2 = tracewire (last parsedinput) (0,0) [(0,0)]
|
|
||||||
print (day3a trace1 trace2)
|
print (day3a trace1 trace2)
|
||||||
print (day3b trace1 trace2)
|
print (day3b trace1 trace2)
|
||||||
|
|
||||||
|
parse :: String -> [[(Char,Int)]]
|
||||||
|
parse = map (map (\x->(head x,read $ tail x))) . map (splitOn ",") . lines
|
||||||
|
|
||||||
parseone :: String -> (Char, Int)
|
gensteps :: [(Char,Int)] -> [V2 Int]
|
||||||
parseone xs = (head xs, read $ tail xs)
|
gensteps = scanl (+) (V2 0 0) . concatMap (\(x,y)->replicate y $ step x)
|
||||||
|
|
||||||
tracewire :: [(Char,Int)] -> (Int,Int) -> [(Int,Int)] -> [(Int,Int)]
|
step :: Char -> V2 Int
|
||||||
tracewire [] _ x = x
|
step x
|
||||||
tracewire ((x,n):xs) (accx,accy) trc
|
| x=='U'=V2 0 1
|
||||||
| x=='U'=tracewire xs (accx,accy+n) (trc++[(accx,accy+i) | i<-[1..n]])
|
| x=='R'=V2 1 0
|
||||||
| x=='R'=tracewire xs (accx+n,accy) (trc++[(accx+i,accy) | i<-[1..n]])
|
| x=='D'=V2 0 (-1)
|
||||||
| x=='D'=tracewire xs (accx,accy-n) (trc++[(accx,accy-i) | i<-[1..n]])
|
| x=='L'=V2 (-1) 0
|
||||||
| x=='L'=tracewire xs (accx-n,accy) (trc++[(accx-i,accy) | i<-[1..n]])
|
|
||||||
|
|
||||||
day3a :: [(Int,Int)] -> [(Int,Int)] -> Int
|
day3a :: [V2 Int] -> [V2 Int] -> Int
|
||||||
day3a xs ys = Set.findMin $ Set.map manhattan (intersections xs ys)
|
day3a xs ys = Set.findMin $ Set.map manhattan (intersections xs ys)
|
||||||
where manhattan (x,y) = abs x + abs y
|
where manhattan (V2 x y) = abs x + abs y
|
||||||
|
|
||||||
intersections :: [(Int,Int)] -> [(Int,Int)] -> Set.Set (Int, Int)
|
intersections :: [V2 Int] -> [V2 Int] -> Set.Set (V2 Int)
|
||||||
intersections xs ys = Set.delete (0,0) crossset
|
intersections xs ys = Set.delete (V2 0 0) crossset
|
||||||
where crossset = (Set.fromList xs) `Set.intersection` (Set.fromList ys)
|
where crossset = (Set.fromList xs) `Set.intersection` (Set.fromList ys)
|
||||||
|
|
||||||
day3b xs ys = minimum [let f = fromJust . findIndex (==x) in f xs + f ys
|
day3b xs ys = minimum [let f = fromJust . findIndex (==x) in
|
||||||
| x<-Set.toList $ intersections xs ys]
|
f xs + f ys | x<-Set.toList $ intersections xs ys]
|
||||||
|
|
Loading…
Reference in New Issue
Block a user