advent-of-code/2023/8/Main2.hs
2023-12-07 23:10:02 -08:00

32 lines
977 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
revTake3 = reverse . take 3
parseLine l = (revTake3 l, (revTake3 $ drop 7 l, revTake3 $ drop 12 l))
main :: IO ()
main = do
allLines <- lines <$> readFile "data.txt"
let directions = cycle $ head allLines
dataMap = getDataMap $ drop 2 allLines
print $ solve directions dataMap