Skip to content

Instantly share code, notes, and snippets.

@kei-q
Created August 14, 2012 16:00
Show Gist options
  • Select an option

  • Save kei-q/3350492 to your computer and use it in GitHub Desktop.

Select an option

Save kei-q/3350492 to your computer and use it in GitHub Desktop.
10.2
type Point = (Int, Int)
type Section = (Int, Int, Int)
data Label = A | B | C deriving Show
data Route = Route { path :: [(Label, Int)], distance :: Int } deriving Show
input :: [Section]
input = [(50, 10, 30), (5, 90, 20), (40, 2, 25), (10, 8, 0)]
zeroRoute :: Route
zeroRoute = Route { path = [], distance = 0 }
getPath :: Route -> [Label]
getPath = reverse . map fst . path
getDistance :: Route -> Int
getDistance = distance
shortestRoute :: [Section] -> Route
shortestRoute sections = let (ra, rb) = foldl next (zeroRoute, zeroRoute) sections
in if distance ra < distance rb then ra else rb
next :: (Route, Route) -> Section -> (Route, Route)
next (Route pa da, Route pb db) (x, y, z) = (a', b')
where
a' | da1 < da2 = Route ((A, x) : pa ) da1
| otherwise = Route ((C, z) : (B, y) : pb) da2
b' | db1 < db2 = Route ((B, y) : pb ) db1
| otherwise = Route ((C, z) : (A, x) : pa) db2
(da1, da2) = (da + x, db + y + z)
(db1, db2) = (db + y, da + x + z)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment