advent-of-code/2023/8/Main2.hs

35 lines
959 B
Haskell
Raw Normal View History

2023-12-07 23:10:02 -08:00
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:_)
2023-12-11 20:14:45 -08:00
| s == 'Z' = id
2023-12-07 23:10:02 -08:00
| otherwise = countTimes' ds (getDirection d $ m HMS.! ss) . succ
solve :: String -> DataMap -> Int
2023-12-11 20:14:45 -08:00
solve directions m = foldl1' lcm
. map (countTimes directions m)
. filter ((== 'A') . head)
. HMS.keys
$ m
2023-12-07 23:10:02 -08:00
getDataMap :: [String] -> DataMap
getDataMap = HMS.fromList . map parseLine
where
2023-12-11 20:14:45 -08:00
get3At x = reverse . take 3 . drop x
parseLine l = (get3At 0 l, (get3At 7 l, get3At 12 l))
2023-12-07 23:10:02 -08:00
main :: IO ()
main = do
allLines <- lines <$> readFile "data.txt"
2023-12-11 20:14:45 -08:00
let directions = cycle . head $ allLines
print . solve directions . getDataMap . drop 2 $ allLines