r/adventofcode • • Dec 04 '18

SOLUTION MEGATHREAD -πŸŽ„- 2018 Day 4 Solutions -πŸŽ„-

--- Day 4: Repose Record ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 4

Transcript:

Today’s puzzle would have been a lot easier if my language supported ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

36 Upvotes

340 comments sorted by

View all comments

1

u/[deleted] Dec 05 '18 edited Dec 05 '18

Extremely over-engineered Haskell solution:

module Main where

import Data.Maybe (mapMaybe)
import Text.ParserCombinators.ReadP (
  ReadP, readP_to_S, char, string, munch1
  )
import Data.Char (isDigit)
import Data.List (sort)
import Control.Applicative ((<|>))
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as M
import Control.Monad.Trans.State.Strict
import Data.Functor (($>))
import Control.Arrow (first, second, (&&&))
import Control.Monad (guard)

data Action = Begin Int | Sleep | Wake
  deriving (Show, Eq, Ord)

data Entry = Entry {
  year :: Int, month :: Int, day :: Int,
  hour :: Int, minute :: Int,
  action :: Action
  } deriving (Show, Eq, Ord)

number :: ReadP Int
number = read <$> munch1 isDigit

parseAction :: ReadP Action
parseAction =
  fmap Begin (string "Guard #" *> number <* string " begins shift") <|>
  (string "falls asleep" $> Sleep) <|>
  (string "wakes up" $> Wake)

entry :: ReadP Entry
entry = do
  year   <- char '[' *> number
  month  <- char '-' *> number
  day    <- char '-' *> number
  hour   <- char ' ' *> number
  minute <- char ':' *> number
  action <- string "] " *> parseAction
  return $ Entry year month day hour minute action

parse :: String -> Maybe Entry
parse s = case readP_to_S entry s of
  [(res, [])] -> Just res
  _           -> Nothing

processEntries :: [String] -> [Entry]
processEntries = sort . mapMaybe parse

--                 guard   minute freq
type EventState = (IntMap (IntMap Word), [Entry])

nextEvent :: State EventState ()
nextEvent = do
  (m, events) <- get
  case events of
    (x:xs) -> put (m, xs)
    []     -> return ()

begin :: State EventState Bool
begin = do
  events <- gets snd
  nextEvent
  case action <$> events of
    (Begin gId:Sleep:_)   -> sleep gId    -- guard falls asleep
    (Begin _:Begin _:_)   -> begin        -- guard didn't sleep at all
    _                     -> return False -- invalid

sleep :: Int -> State EventState Bool
sleep gId = do
  events <- gets snd
  nextEvent
  case (action &&& minute) <$> events of
    ((Sleep, start):_) -> wake gId start -- guard wakes up
    _                  -> return False   -- invalid

wake :: Int -> Int -> State EventState Bool
wake gId start = do
  events <- gets snd
  nextEvent
  case action <$> events of
    (Wake:es) -> do
        let end     = minute $ head events
            minutes = M.fromDistinctAscList [(n, 1) | n <- [start..end - 1]]
        modify $ first $ M.insertWith (M.unionWith (+)) gId minutes
        case es of
          []          -> return True  -- success, last event in list was wake
          (Begin _:_) -> begin        -- new guard starts
          (Sleep:_)   -> sleep gId    -- guard goes back to sleep
          _           -> return False -- invalid
    _         -> return False         -- invalid

run :: [String] -> (Bool, IntMap (IntMap Word))
run xs = second fst $ runState begin (M.empty, sort $ mapMaybe parse xs)

part1 :: [String] -> Maybe Int
part1 xs = do
  let (success, coverage) = run xs
  guard success
  let ((g, _, m, _), _) = M.mapAccumWithKey argMax (0, 0, 0, 0) coverage
  return $ g * m
  where 
    argMax c@(bestGuard, bestTotal, bestMinute, bestCount) gId m =
      let (total, largest, minute') = compact m
      in  if total > bestTotal
          then ((gId, total, minute', largest), ())
          else (c, ())
    compact = M.foldlWithKey' f (0, 0, 0)
    f (total, largest, m) minute' count =
      if count > largest
      then (count + total, count, minute')
      else (count + total, largest, m)

part2 :: [String] -> Maybe Int
part2 xs = do
  let (success, coverage) = run xs
  guard success
  let ((g, m, _), _) = M.mapAccumWithKey argMax (0, 0, 0) coverage
  return $ g * m
  where
    argMax c@(bestGuard, bestMinute, bestCount) gId m =
      let (largest, minute') = compact m
      in  if largest > bestCount
          then ((gId, minute', largest), ())
          else (c, ())
    compact = M.foldlWithKey' f (0, 0)
    f (largest, m) minute' count =
      if count > largest
      then (count, minute')
      else (largest, m)

main :: IO ()
main = do
  input <- lines <$> readFile "input4.txt"
  print $ part1 input
  print $ part2 input