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!

42 Upvotes

340 comments sorted by

View all comments

Show parent comment

1

u/nirgle Dec 04 '18

I created a new Record data type with three constructors matching the three line types:

data Record = BeginShift  Timestamp BadgeID
            | FallsAsleep Timestamp
            | WakesUp     Timestamp
            deriving (Show)

parseRecord :: Parser Record
parseRecord = begins <|> fallsAsleep <|> wakesUp

-- [1518-11-01 00:00] Guard #10 begins shift
-- [1518-11-01 00:05] falls asleep
-- [1518-11-01 00:25] wakes up
begins, fallsAsleep, wakesUp :: Parser Record
begins      = BeginShift  <$> timestamp <* string " Guard #" <*> number <* string " begins shift"
fallsAsleep = FallsAsleep <$> timestamp <* string " falls asleep"
wakesUp     = WakesUp     <$> timestamp <* string " wakes up"

I built up the list of guard/minutes asleep using a bit of recursion and pattern matching:

-- Analyze a (sorted) list of records to determine which minutes
-- of the night were slept through by which guards
analyze :: [Record] -> [(BadgeID, Minute)]
analyze rs = go 0 rs

  where go :: BadgeID -> [Record] -> [(BadgeID, Minute)]

        -- Switch the guard we're analyzing
        go _ (BeginShift _ badge : rs) = go badge rs

        -- A FallsAsleep record is always followed by a WakesUp record, so pattern match on this pair
        go badge (FallsAsleep a : WakesUp w : rs) 
            = minutes badge a w ++ go badge rs

        go _ [] = []

        -- In our puzzle input, guards don't fall asleep before midnight, which simplifies this
        minutes b a w = [ (b, minute a + i) | i <- [0 .. minute w - minute a - 1] ]