-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.hs
40 lines (31 loc) · 1.22 KB
/
main.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import Text.Parsec
import Text.Parsec.String (parseFromFile)
import qualified Data.Map as Map
import Data.Maybe
import Data.List
import Control.Monad
type City = String
type DistanceTable = Map.Map (City, City) Int
distanceTable :: Parsec String u DistanceTable
distanceTable = Map.fromList <$> many (distance <* endOfLine) <* eof
where distance = (,) <$> cities <* string " = " <*> value
cities = (,) <$> city <* string " to " <*> city
value = read <$> many1 digit
city = (:) <$> upper <*> many letter
pairs :: [a] -> [(a, a)]
pairs x = zip x $ tail x
distance :: (City, City) -> DistanceTable -> Int
distance (f, t) = fmap fromJust $ mplus <$> Map.lookup (t, f) <*> Map.lookup (f, t)
routeLength :: [City] -> DistanceTable -> Int
routeLength = liftM sum . mapM distance . pairs
cities :: DistanceTable -> [City]
cities = nub . ap [fst, snd] . Map.keys
routeLengths :: DistanceTable -> [Int]
routeLengths = mapM routeLength . permutations =<< cities
fromRight :: Show a => Either a b -> b
fromRight = either (error . show) id
main :: IO()
main = mainP2 where
mainP1 = main' minimum
mainP2 = main' maximum
main' f = parseFromFile distanceTable "input.txt" >>= print . f . routeLengths . fromRight