From e263d2ae691ba005087c345da236793e2e895a8d Mon Sep 17 00:00:00 2001 From: Siphalor Date: Tue, 17 Dec 2024 19:43:22 +0100 Subject: [PATCH] Day sixteen part one --- day-16-haskell/.gitignore | 2 + day-16-haskell/Setup.hs | 2 + day-16-haskell/app/Main.hs | 18 +++ day-16-haskell/day16-haskell.cabal | 52 ++++++++ day-16-haskell/package.yaml | 49 +++++++ day-16-haskell/src/Lib.hs | 205 +++++++++++++++++++++++++++++ day-16-haskell/stack.yaml | 67 ++++++++++ day-16-haskell/stack.yaml.lock | 13 ++ day-16-haskell/test/Spec.hs | 2 + 9 files changed, 410 insertions(+) create mode 100644 day-16-haskell/.gitignore create mode 100644 day-16-haskell/Setup.hs create mode 100644 day-16-haskell/app/Main.hs create mode 100644 day-16-haskell/day16-haskell.cabal create mode 100644 day-16-haskell/package.yaml create mode 100644 day-16-haskell/src/Lib.hs create mode 100644 day-16-haskell/stack.yaml create mode 100644 day-16-haskell/stack.yaml.lock create mode 100644 day-16-haskell/test/Spec.hs diff --git a/day-16-haskell/.gitignore b/day-16-haskell/.gitignore new file mode 100644 index 0000000..c368d45 --- /dev/null +++ b/day-16-haskell/.gitignore @@ -0,0 +1,2 @@ +.stack-work/ +*~ \ No newline at end of file diff --git a/day-16-haskell/Setup.hs b/day-16-haskell/Setup.hs new file mode 100644 index 0000000..9a994af --- /dev/null +++ b/day-16-haskell/Setup.hs @@ -0,0 +1,2 @@ +import Distribution.Simple +main = defaultMain diff --git a/day-16-haskell/app/Main.hs b/day-16-haskell/app/Main.hs new file mode 100644 index 0000000..a7cfe06 --- /dev/null +++ b/day-16-haskell/app/Main.hs @@ -0,0 +1,18 @@ +module Main (main) where + +import System.Environment.Blank ( getArgs ) +import Lib (task1, task2) + +main :: IO () +main = do + args <- getArgs + case args of + ["1", file] -> do + input <- readFile file + result <- task1 input + print result + ["2", file] -> do + input <- readFile file + result <- task2 input + print result + _ -> error "Usage: <1|2> " diff --git a/day-16-haskell/day16-haskell.cabal b/day-16-haskell/day16-haskell.cabal new file mode 100644 index 0000000..ee05355 --- /dev/null +++ b/day-16-haskell/day16-haskell.cabal @@ -0,0 +1,52 @@ +cabal-version: 2.2 + +-- This file has been generated from package.yaml by hpack version 0.37.0. +-- +-- see: https://github.com/sol/hpack + +name: day16-haskell +version: 0.1.0.0 +homepage: https://github.com/Siphalor/day16-haskell#readme +bug-reports: https://github.com/Siphalor/day16-haskell/issues +author: Siphalor +maintainer: info@siphalor.de +copyright: Siphalor +license: BSD-3-Clause +build-type: Simple + +source-repository head + type: git + location: https://github.com/Siphalor/day16-haskell + +library + exposed-modules: + Lib + hs-source-dirs: + src + ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints + build-depends: + base >=4.7 && <5 + , containers + , flow + default-language: Haskell2010 + +executable day16-haskell-exe + main-is: Main.hs + hs-source-dirs: + app + ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints -threaded -rtsopts -with-rtsopts=-N + build-depends: + base >=4.7 && <5 + , day16-haskell + default-language: Haskell2010 + +test-suite day16-haskell-test + type: exitcode-stdio-1.0 + main-is: Spec.hs + hs-source-dirs: + test + ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints -threaded -rtsopts -with-rtsopts=-N + build-depends: + base >=4.7 && <5 + , day16-haskell + default-language: Haskell2010 diff --git a/day-16-haskell/package.yaml b/day-16-haskell/package.yaml new file mode 100644 index 0000000..355e534 --- /dev/null +++ b/day-16-haskell/package.yaml @@ -0,0 +1,49 @@ +name: day16-haskell +version: 0.1.0.0 +github: "Siphalor/day16-haskell" +license: BSD-3-Clause +author: "Siphalor" +maintainer: "info@siphalor.de" +copyright: "Siphalor" +spec-version: 0.36.0 + +dependencies: +- base >= 4.7 && < 5 + +ghc-options: +- -Wall +- -Wcompat +- -Widentities +- -Wincomplete-record-updates +- -Wincomplete-uni-patterns +- -Wmissing-home-modules +- -Wpartial-fields +- -Wredundant-constraints + +library: + source-dirs: src + dependencies: + - flow + - containers + +executables: + day16-haskell-exe: + main: Main.hs + source-dirs: app + ghc-options: + - -threaded + - -rtsopts + - -with-rtsopts=-N + dependencies: + - day16-haskell + +tests: + day16-haskell-test: + main: Spec.hs + source-dirs: test + ghc-options: + - -threaded + - -rtsopts + - -with-rtsopts=-N + dependencies: + - day16-haskell diff --git a/day-16-haskell/src/Lib.hs b/day-16-haskell/src/Lib.hs new file mode 100644 index 0000000..5297206 --- /dev/null +++ b/day-16-haskell/src/Lib.hs @@ -0,0 +1,205 @@ +{-# LANGUAGE NamedFieldPuns #-} + +module Lib where + +import Control.Monad (join) +import Flow +import qualified Data.Map.Strict as Map +import Data.Maybe (listToMaybe, maybeToList) +import qualified Data.Set as Set +import Text.ParserCombinators.ReadP + +type IntType = Int + +data Vec2 = Vec2 IntType IntType + deriving (Eq, Ord, Show) +vAdd :: Vec2 -> Vec2 -> Vec2 +vAdd (Vec2 aX aY) (Vec2 bX bY) = Vec2 (aX+bX) (aY+bY) + +data Direction = North | East | South | West + deriving (Eq, Ord, Show) +dOpposite :: Direction -> Direction +dOpposite North = South +dOpposite East = West +dOpposite South = North +dOpposite West = East +dVec :: Direction -> Vec2 +dVec North = Vec2 0 (-1) +dVec East = Vec2 1 0 +dVec South = Vec2 0 1 +dVec West = Vec2 (-1) 0 + +data Tile = Path | Start | End | Wall + deriving (Eq, Ord, Show) + +type WorldMap = Map.Map Vec2 Tile + +data Edge = Edge { eDirFrom :: Direction, eFrom :: Vec2, eDirTo :: Direction, eTo :: Vec2, ePrice :: Int } + deriving (Show) + +type WorldGraphEdges = Map.Map Vec2 [Edge] +data WorldGraph = WorldGraph { wStart :: Vec2, wEnd :: Vec2, wEdges :: WorldGraphEdges } + deriving (Show) + +task1 :: String -> IO IntType +task1 input = + let worldMap = parseFile input + rawGraph = mapToGraph worldMap + in do + --rawGraph |> wEdges |> Map.elems |> join |> showEdgesSimple |> putStrLn + worldGraph <- simplifyGraph rawGraph + worldGraph |> wEdges |> Map.elems |> join |> showEdgesSimple |> putStrLn + --return $ expectJust "No path found" $ findBestPath worldGraph [(wStart worldGraph, East)] + bestPath <- dijkstra worldGraph Map.empty (Map.singleton (wStart worldGraph, East) 0) + return $ expectJust "No path found" $ bestPath + +task2 :: String -> IO IntType +task2 _ = return 2 + +showEdgesSimple :: [Edge] -> String +showEdgesSimple [] = "" +showEdgesSimple (edge:edges) = (show $ eFrom edge) ++ " -> " ++ (show $ eTo edge) ++ ": " ++ (show $ ePrice edge) ++ "\n" ++ (showEdgesSimple edges) + +dijkstra :: WorldGraph -> Map.Map (Vec2, Direction) Int -> Map.Map (Vec2, Direction) Int -> IO (Maybe Int) +dijkstra world@WorldGraph { wEdges, wEnd } done unvisited + | null unvisited = + [North, East, South, West] |> map (\d -> done Map.!? (wEnd, d) |> maybeToList) |> join |> minimum |> pure |> return + | otherwise = + let ((pos, dir), cost) = findNext + outgoing = Map.findWithDefault [] pos wEdges + unvisitedOutgoing = outgoing |> filter (\Edge { eTo, eDirTo } -> Map.notMember (eTo, eDirTo) done) + unvisitedOutgoingWithPrice = unvisitedOutgoing |> map (\e@Edge { eDirFrom, ePrice } -> (e, if dir == dOpposite eDirFrom then cost + ePrice else cost + ePrice + 1000)) :: [(Edge, IntType)] + unvisitedWithoutCurrent = Map.delete (pos, dir) unvisited + nextUnvisited = foldr (\(Edge { eTo, eDirTo }, price) -> Map.alter (pure . maybe price (min price)) (eTo, eDirTo)) unvisitedWithoutCurrent unvisitedOutgoingWithPrice + nextDone = Map.insert (pos, dir) cost done + in do + -- putStrLn $ "Processing " ++ (show pos) ++ "/" ++ (show dir) + -- print nextUnvisited + dijkstra world nextDone nextUnvisited + where + findNext :: ((Vec2, Direction), Int) + findNext = + let options = unvisited |> Map.assocs + in foldr (\a@(_,aC) b@(_,bC) -> if aC < bC then a else b) (head options) (drop 1 options) + +findBestPath :: WorldGraph -> [(Vec2, Direction)] -> Maybe Int +findBestPath _ [] = error "Must call findBestPath with an initial position" +findBestPath world@WorldGraph { wEdges, wEnd } ((lastPos, lastDir):path) = + let edgeOptions = wEdges Map.!? lastPos |> expectJust ("Position is missing in map " ++ show lastPos) |> filter (\Edge{eTo=optTo} -> not $ listContains optTo $ map (\(p,_) -> p) path) + in case edgeOptions |> map (maybeToList . exploreOption) |> join of + [] -> Nothing + prices -> return $ minimum prices + where + exploreOption :: Edge -> Maybe Int + exploreOption edge@Edge{ePrice, eDirFrom, eTo, eDirTo} + | eTo == wEnd = Just hopPrize + | otherwise = findBestPath world ((eTo, eDirTo):(lastPos, lastDir):path) |> fmap (\pr -> pr + hopPrize) + where + hopPrize :: Int + hopPrize = if eDirFrom == dOpposite lastDir then ePrice else ePrice + 1000 + +mapToGraph :: WorldMap -> WorldGraph +mapToGraph worldMap = + let start = Map.assocs worldMap |> filter (\(_, t) -> t == Start) |> listToMaybe |> expectJust "No start found" |> entryKey + end = Map.assocs worldMap |> filter (\(_, t) -> t == End) |> listToMaybe |> expectJust "No end found" |> entryKey + pathMap = worldMap |> Map.filter ((/=) Wall) + edges = pathMap |> Map.keys |> map edgesFromPos |> join + edgesByFrom = map (\e -> (eFrom e, [e])) edges |> Map.fromListWith (++) + in WorldGraph { wStart = start, wEnd = end, wEdges = edgesByFrom } + + where + edgesFromPos :: Vec2 -> [Edge] + edgesFromPos pos = + [North, East, South, West] + |> map (\dir -> dVec dir |> vAdd pos |> \t -> if validTarget $ worldMap Map.!? t then [Edge { eDirTo = dir, eTo = t, eDirFrom = dOpposite dir, eFrom = pos, ePrice = 1 }] else []) + |> join + + validTarget :: Maybe Tile -> Bool + validTarget (Just Wall) = False + validTarget (Just _) = True + validTarget _ = False + +simplifyGraph :: WorldGraph -> IO WorldGraph +simplifyGraph world@WorldGraph { wStart, wEnd, wEdges } = + case Map.assocs wEdges |> filter (\(p, edges) -> p /= wStart && p /= wEnd && length edges <= 2) of + [] -> return world + ((pos, []):_) -> simplifyGraph WorldGraph { wStart, wEnd, wEdges = Map.delete pos wEdges } + ((_, [e]):_) -> do + --putStrLn $ "Removing " ++ (show e) + simplifyGraph WorldGraph { wStart, wEnd, wEdges = removeEdge e wEdges } + ((_, [e1, e2]):_) -> + let newEdges = wEdges |> combineEdges e1 e2 + in do + --putStrLn $ "Combining " ++ (show e1) ++ " : " ++ (show e2) + simplifyGraph WorldGraph { wStart, wEnd, wEdges = newEdges } + _ -> error "Ureachable in simplifyGraph" + where + combineEdges :: Edge -> Edge -> WorldGraphEdges -> WorldGraphEdges + combineEdges e1@Edge { eDirFrom = eDirFrom1, eTo = eTo1, eDirTo = eDirTo1, ePrice = ePrice1 } e2@Edge { eDirFrom = eDirFrom2, eTo = eTo2, eDirTo = eDirTo2, ePrice = ePrice2 } edges = + let combinedPrice = ePrice1 + ePrice2 + if eDirFrom1 == dOpposite eDirFrom2 then 0 else 1000 + in edges |> removeEdge e1 |> removeEdge e2 + |> Map.adjust (\es -> Edge { eFrom = eTo1, eDirFrom = eDirTo1, eTo = eTo2, eDirTo = eDirTo2, ePrice = combinedPrice }:es) eTo1 + |> Map.adjust (\es -> Edge { eFrom = eTo2, eDirFrom = eDirTo2, eTo = eTo1, eDirTo = eDirTo1, ePrice = combinedPrice }:es) eTo2 + + removeEdge :: Edge -> WorldGraphEdges -> WorldGraphEdges + removeEdge Edge { eFrom, eTo } edgesMap = + edgesMap + |> Map.adjust (\edges -> edges |> filter (not . (isEdgeTo eTo))) eFrom + |> Map.adjust (\edges -> edges |> filter (not . (isEdgeTo eFrom))) eTo + + isEdgeTo :: Vec2 -> Edge -> Bool + isEdgeTo testTo Edge { eTo } = testTo == eTo + +parseFile :: String -> WorldMap +parseFile input = + case readP_to_S parse input of + [] -> error "Failed to parse" + ((v,_):_) -> v + + where + parse :: ReadP WorldMap + parse = do + worldMap <- parseWorld + _ <- eof + return worldMap + +parseWorld :: ReadP WorldMap +parseWorld = do + ls <- many1 parseLine + zip [0..] ls |> map (\(y, line) -> zip [0..] line |> map (\(x, c) -> (Vec2 x y, toTile c))) |> join |> Map.fromList |> return + + where + parseLine :: ReadP String + parseLine = do + content <- munch1 (not . isNewLine) + _ <- char '\n' + return content + + toTile :: Char -> Tile + toTile '.' = Path + toTile 'S' = Start + toTile 'E' = End + toTile '#' = Wall + toTile c = error $ "Unknown tile: " ++ [c] + +isNewLine :: Char -> Bool +isNewLine = (==) '\n' + +listContains :: Eq a => a -> [a] -> Bool +listContains _ [] = False +listContains a (e:es) = if a == e then True else listContains a es + +nothingIfEmpty :: Foldable t => t a -> Maybe (t a) +nothingIfEmpty values + | null values = Nothing + | otherwise = Just values + +entryKey :: (a,b) -> a +entryKey (k,_) = k +entryValue :: (a,b) -> b +entryValue (_,v) = v + +expectJust :: String -> Maybe a -> a +expectJust message Nothing = error message +expectJust _ (Just value) = value + diff --git a/day-16-haskell/stack.yaml b/day-16-haskell/stack.yaml new file mode 100644 index 0000000..1620b4f --- /dev/null +++ b/day-16-haskell/stack.yaml @@ -0,0 +1,67 @@ +# This file was automatically generated by 'stack init' +# +# Some commonly used options have been documented as comments in this file. +# For advanced use and comprehensive documentation of the format, please see: +# https://docs.haskellstack.org/en/stable/yaml_configuration/ + +# A 'specific' Stackage snapshot or a compiler version. +# A snapshot resolver dictates the compiler version and the set of packages +# to be used for project dependencies. For example: +# +# snapshot: lts-22.28 +# snapshot: nightly-2024-07-05 +# snapshot: ghc-9.6.6 +# +# The location of a snapshot can be provided as a file or url. Stack assumes +# a snapshot provided as a file might change, whereas a url resource does not. +# +# snapshot: ./custom-snapshot.yaml +# snapshot: https://example.com/snapshots/2024-01-01.yaml +snapshot: + url: https://raw.githubusercontent.com/commercialhaskell/stackage-snapshots/master/lts/23/0.yaml + +# User packages to be built. +# Various formats can be used as shown in the example below. +# +# packages: +# - some-directory +# - https://example.com/foo/bar/baz-0.0.2.tar.gz +# subdirs: +# - auto-update +# - wai +packages: +- . +# Dependency packages to be pulled from upstream that are not in the snapshot. +# These entries can reference officially published versions as well as +# forks / in-progress versions pinned to a git hash. For example: +# +# extra-deps: +# - acme-missiles-0.3 +# - git: https://github.com/commercialhaskell/stack.git +# commit: e7b331f14bcffb8367cd58fbfc8b40ec7642100a +# +# extra-deps: [] + +# Override default flag values for project packages and extra-deps +# flags: {} + +# Extra package databases containing global packages +# extra-package-dbs: [] + +# Control whether we use the GHC we find on the path +# system-ghc: true +# +# Require a specific version of Stack, using version ranges +# require-stack-version: -any # Default +# require-stack-version: ">=3.1" +# +# Override the architecture used by Stack, especially useful on Windows +# arch: i386 +# arch: x86_64 +# +# Extra directories used by Stack for building +# extra-include-dirs: [/path/to/dir] +# extra-lib-dirs: [/path/to/dir] +# +# Allow a newer minor version of GHC than the snapshot specifies +# compiler-check: newer-minor diff --git a/day-16-haskell/stack.yaml.lock b/day-16-haskell/stack.yaml.lock new file mode 100644 index 0000000..a4edf3e --- /dev/null +++ b/day-16-haskell/stack.yaml.lock @@ -0,0 +1,13 @@ +# This file was autogenerated by Stack. +# You should not edit this file by hand. +# For more information, please see the documentation at: +# https://docs.haskellstack.org/en/stable/lock_files + +packages: [] +snapshots: +- completed: + sha256: 9444fadfa30b67a93080254d53872478c087592ad64443e47c546cdcd13149ae + size: 678857 + url: https://raw.githubusercontent.com/commercialhaskell/stackage-snapshots/master/lts/23/0.yaml + original: + url: https://raw.githubusercontent.com/commercialhaskell/stackage-snapshots/master/lts/23/0.yaml diff --git a/day-16-haskell/test/Spec.hs b/day-16-haskell/test/Spec.hs new file mode 100644 index 0000000..cd4753f --- /dev/null +++ b/day-16-haskell/test/Spec.hs @@ -0,0 +1,2 @@ +main :: IO () +main = putStrLn "Test suite not yet implemented"