2023 day 8: add Haskell solution

This commit is contained in:
eriedaberrie 2023-12-07 23:10:02 -08:00
parent 6e95a83496
commit bab443b919
3 changed files with 58 additions and 0 deletions

1
.gitignore vendored
View file

@ -4,6 +4,7 @@
*data*.txt *data*.txt
[Mm]ain [Mm]ain
[Mm]ain-[0-9] [Mm]ain-[0-9]
[Mm]ain[0-9]
# Nix stuff # Nix stuff
result* result*

26
2023/8/Main1.hs Normal file
View file

@ -0,0 +1,26 @@
import qualified Data.HashMap.Strict as HMS
type DataMap = HMS.HashMap String (String, String)
getDirection :: Char -> (a, a) -> a
getDirection 'L' = fst
getDirection 'R' = snd
countTimes :: String -> DataMap -> Int
countTimes directions m = countTimes' directions "AAA" 0
where
countTimes' (d:ds) s
| s == "ZZZ" = id
| otherwise = countTimes' ds (getDirection d $ m HMS.! s) . succ
getDataMap :: [String] -> DataMap
getDataMap = HMS.fromList . map parseLine
where
parseLine l = (take 3 l, (take 3 $ drop 7 l, take 3 $ drop 12 l))
main :: IO ()
main = do
allLines <- lines <$> readFile "data.txt"
let directions = cycle $ head allLines
dataMap = getDataMap $ drop 2 allLines
print $ countTimes directions dataMap

31
2023/8/Main2.hs Normal file
View file

@ -0,0 +1,31 @@
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