diff --git a/83.hs b/83.hs index ae6789e..96576ea 100644 --- a/83.hs +++ b/83.hs @@ -16,8 +16,8 @@ instance Monoid Element where case getMin v1 v2 of 0 -> mempty v -> if v == v1 - then Element v1 Visited p1 - else Element v2 Visited p2 + then Element v1 Visited p1 + else Element v2 Visited p2 getMin :: Value -> Value -> Value getMin v1 0 = v1 diff --git a/83_alt b/83_alt new file mode 100644 index 0000000..f6d4461 Binary files /dev/null and b/83_alt differ diff --git a/83_alt.hi b/83_alt.hi new file mode 100644 index 0000000..e77d342 Binary files /dev/null and b/83_alt.hi differ diff --git a/83_alt.hs b/83_alt.hs new file mode 100644 index 0000000..2a377a7 --- /dev/null +++ b/83_alt.hs @@ -0,0 +1,62 @@ +import Data.List.Split +import Data.Matrix +import Data.Maybe +import Data.Foldable +import Data.PQueue.Min + +type Value = Integer +type Distance = Maybe Integer -- Nothing represents infinity +type Position = (Int, Int) +data Element = Element { + value :: Value, + distance :: Distance, + position :: Position + } deriving (Eq, Show) +data PQE = PQE Element Distance deriving (Eq, Show) + +instance Ord PQE where + PQE _ Nothing <= _ = False + _ <= PQE _ Nothing = True + PQE _ (Just d1) <= PQE _ (Just d2) = d1 <= d2 + +dijkstra :: Matrix Element -> MinQueue PQE -> Position -> Distance +dijkstra m q p = + let PQE minElement minDistance = findMin q + in if position minElement == p + then distance minElement + else undefined --TODO + + +findShortestPathLength :: Matrix Element -> Distance +findShortestPathLength m = + let initialElement = m ! (1, 1) + initialMinQ = singleton $ PQE initialElement $ distance initialElement + lastPos = (nrows m, ncols m) + in dijkstra m initialMinQ lastPos + + +setInitial :: Matrix Element -> Matrix Element +setInitial m = + let v = value $ m ! (1, 1) + maybeMatrix = safeSet (Element v (Just v) (1, 1)) (1, 1) m + in case maybeMatrix of + Just mm -> mm + Nothing -> m + +initElement :: Matrix Integer -> Position -> Element +initElement m p = + let value = m ! p + in Element value Nothing p + +toElementMatrix :: Matrix Integer -> Matrix Element +toElementMatrix m = + matrix (nrows m) (ncols m) (initElement m) + +main :: IO () +main = do + contents <- readFile "p083_matrix.txt" + let listsMatrix = fmap (fmap read . (splitOn ",")) $ lines contents :: [[Integer]] + valueMatrix = fromLists listsMatrix + unvisitedMatrix = toElementMatrix valueMatrix + mtrx = setInitial unvisitedMatrix + print $ findShortestPathLength mtrx \ No newline at end of file diff --git a/83_alt.o b/83_alt.o new file mode 100644 index 0000000..0869e4d Binary files /dev/null and b/83_alt.o differ