Advertisement
Guest User

Untitled

a guest
Apr 19th, 2015
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. import Data.List
  2.  
  3. data Section = Section {getA :: Int, getB :: Int, getC :: Int }
  4. deriving (Show)
  5.  
  6. type RoadSystem = [Section]
  7.  
  8. heathrowToLondon :: RoadSystem
  9. heathrowToLondon = [Section 50 10 30,
  10. Section 5 90 20,
  11. Section 40 2 25,
  12. Section 10 8 0]
  13.  
  14. data Label = A | B | C deriving (Show)
  15.  
  16. type Path = [(Label, Int)]
  17.  
  18.  
  19. roadStep :: (Path, Path) -> Section -> (Path, Path)
  20. roadStep (pathA, pathB) (Section a b c) =
  21. let timeA = sum (map snd pathA)
  22. timeB = sum (map snd pathB)
  23. forwardTimeToA = timeA + a
  24. crossTimeToA = timeB + b + c
  25. forwardTimeToB = timeB + b
  26. crossTimeToB = timeA + a + c
  27. newPathToA = if forwardTimeToA <= crossTimeToA
  28. then (A, a): pathA
  29. else (C, c) :(B, b):pathB
  30. newPathToB = if forwardTimeToB <= crossTimeToB
  31. then (B, b) : pathB
  32. else (C, c) : (A, a) : pathA
  33. in (newPathToA, newPathToB)
  34.  
  35. optimalPath :: RoadSystem -> Path
  36. optimalPath roadSystem =
  37. let (bestAPath, bestBPath) = foldl roadStep ([], []) roadSystem
  38. in if sum (map snd bestAPath) <= sum (map snd bestBPath)
  39. then reverse bestAPath
  40. else reverse bestBPath
  41.  
  42. groupsOf :: Int -> [a] -> [[a]]
  43. groupsOf 0 _ = undefined
  44. groupsOf _ [] = []
  45. groupsOf n xs = take n xs : (groupsOf n . drop n $ xs)
  46.  
  47. -- undefined :: a
  48.  
  49. main :: IO ()
  50. main = do
  51. contents <- getContents
  52. let threes = groupsOf 3 . map read . lines $ contents
  53. roadSystem = map (\ [a, b, c] -> Section a b c) threes
  54. path = optimalPath roadSystem
  55. pathString = concat $ map (show . fst) path
  56. pathTime = sum $ map snd path
  57. putStrLn $ "The best path to take is :" ++ pathString
  58. putStrLn $ "Time taken :" ++ show pathTime
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement