2018/Day04/Day4A.hs

50 lines
1.5 KiB
Haskell

#!/usr/bin/env stack
-- stack --resolver lts-12.5 script
-- WORK IN PROGRESS
module Day4A where
import Data.List (sort)
import Data.Maybe (listToMaybe, mapMaybe, fromJust)
import Data.Time.Clock
import Data.Time.Format
import Debug.Trace
import Text.Regex.TDFA
import qualified Data.IntMap as IM
import qualified Data.Vector as V
handleGuardSwitch :: String -> Maybe Int
handleGuardSwitch x = unwrap <$> matches
where matches = listToMaybe (x =~ "#([0-9]+)")
unwrap (_:id:_) = read id
parseGuardWake :: String -> Maybe Int
parseGuardWake x = unwrap <$> listToMaybe (x =~ "(\\d{2})\\] wakes up")
where unwrap (_:y:_) = read y
parseGuardSleep :: String -> Maybe Int
parseGuardSleep x = unwrap <$> listToMaybe (x =~ "(\\d{2})\\] falls asleep")
where unwrap (_:y:_) = read y
handle' :: [String] -> Maybe Int -> IM.IntMap V.Vector -> Int -> Bool -> IM.IntMap V.Vector
handle' [] _ minutes _ _ = minutes
handle' (x:xs) guard minutes minute asleep
| Just id <- handleGuardSwitch x = handle' xs (Just id) minutes minute asleep
| Just nextMinute <- parseGuardSleep x = handle' xs guard minutes nextMinute True
| Just nextMinute <- parseGuardWake x =
case (nextMinute < minute) of
True -> handle' (x:xs) guard minutes (minute + 1) True
False -> handle' xs guard minutes minute False
| otherwise =
handle' xs guard minutes (minute + 1) asleep
handle :: [String] -> IM.IntMap V.Vector
handle lines = handle' lines Nothing IM.empty 0 False
main :: IO ()
main = interact $ show . handle . sort . lines