35 lines
959 B
Haskell
35 lines
959 B
Haskell
import qualified Data.HashMap.Strict as HMS
|
|
import Data.List (foldl1')
|
|
|
|
type DataMap = HMS.HashMap String (String, String)
|
|
|
|
getDirection :: Char -> (a, a) -> a
|
|
getDirection 'L' = fst
|
|
getDirection 'R' = snd
|
|
|
|
countTimes :: String -> DataMap -> String -> Int
|
|
countTimes directions m start = countTimes' directions start 0
|
|
where
|
|
countTimes' (d:ds) ss@(s:_)
|
|
| s == 'Z' = id
|
|
| otherwise = countTimes' ds (getDirection d $ m HMS.! ss) . succ
|
|
|
|
solve :: String -> DataMap -> Int
|
|
solve directions m = foldl1' lcm
|
|
. map (countTimes directions m)
|
|
. filter ((== 'A') . head)
|
|
. HMS.keys
|
|
$ m
|
|
|
|
getDataMap :: [String] -> DataMap
|
|
getDataMap = HMS.fromList . map parseLine
|
|
where
|
|
get3At x = reverse . take 3 . drop x
|
|
parseLine l = (get3At 0 l, (get3At 7 l, get3At 12 l))
|
|
|
|
main :: IO ()
|
|
main = do
|
|
allLines <- lines <$> readFile "data.txt"
|
|
let directions = cycle . head $ allLines
|
|
print . solve directions . getDataMap . drop 2 $ allLines
|