summaryrefslogtreecommitdiff
path: root/2019/3.hs
diff options
context:
space:
mode:
authorTom Smeding <tom.smeding@gmail.com>2019-12-03 08:27:18 +0100
committerTom Smeding <tom.smeding@gmail.com>2019-12-03 08:27:25 +0100
commit3db31c460b642abc321bfc53f22d61b5023d2ed6 (patch)
tree1d4f05581c123fc176638133386e934dcc225fc6 /2019/3.hs
parenta0dcb65e4b69ff41014b929ae46fac4ec1754932 (diff)
Day 3a
Diffstat (limited to '2019/3.hs')
-rw-r--r--2019/3.hs55
1 files changed, 55 insertions, 0 deletions
diff --git a/2019/3.hs b/2019/3.hs
new file mode 100644
index 0000000..7f0180a
--- /dev/null
+++ b/2019/3.hs
@@ -0,0 +1,55 @@
+module Main where
+
+import Data.Char
+import Data.List
+import qualified Data.Set as Set
+
+import Input
+
+
+data Pt = Pt Int Int deriving (Show, Eq, Ord)
+data Dir = U | L | D | R deriving (Show)
+data Seg = Seg Pt Dir Int deriving (Show)
+
+direction :: Dir -> Pt
+direction U = Pt 0 1
+direction R = Pt 1 0
+direction D = Pt 0 (-1)
+direction L = Pt (-1) 0
+
+add :: Pt -> Pt -> Pt
+add (Pt x y) (Pt a b) = Pt (x + a) (y + b)
+
+scale :: Int -> Pt -> Pt
+scale n (Pt x y) = Pt (n * x) (n * y)
+
+parse :: String -> [(Dir, Int)]
+parse "" = []
+parse (c:s) =
+ let dir = case c of
+ 'U' -> U
+ 'R' -> R
+ 'D' -> D
+ 'L' -> L
+ _ -> undefined
+ (ns, r) = span isDigit s
+ in (dir, read ns) : parse (dropWhile (== ',') r)
+
+process :: Pt -> [(Dir, Int)] -> [Seg]
+process _ [] = []
+process pt ((dir, n) : rest) =
+ Seg pt dir n : process (add pt (scale n (direction dir))) rest
+
+points :: Seg -> [Pt]
+points (Seg pt dir n) =
+ let delta = direction dir
+ in [add pt (scale k delta) | k <- [1..n]]
+
+manhattan :: Pt -> Int
+manhattan (Pt x y) = abs x + abs y
+
+main :: IO ()
+main = do
+ ls <- map (process (Pt 0 0) . parse) <$> getInput 3
+ let pts = Set.toList (foldl1 Set.intersection (map (Set.fromList . concatMap points) ls))
+ print (manhattan (head (sortOn manhattan pts)))