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!

37 Upvotes

340 comments sorted by

View all comments

1

u/jorosp Dec 05 '18

Haskell

I originally had a fancy parsing function and records and such but once I realized I only needed the minutes I tossed that all in the trash.

{-# LANGUAGE ViewPatterns #-}
import Data.Char
import Data.Maybe
import Data.List
import Data.List.Split
import Data.Function

type Minute  = Int
type GuardID = Int
data Event = Begin GuardID | Sleep Minute deriving (Eq, Ord, Show)

reduce :: (a -> a -> a) -> [a] -> a
reduce f (x:xs) = foldl f x xs

parseLine :: String -> Maybe Event
parseLine = parseLine' . filter (isDigit . head) . groupBy ((==) `on` isDigit)
  where
    parseLine' [_, _, _, _, read -> minute]     = Just (Sleep minute)
    parseLine' [_, _, _, _, _, read -> guardID] = Just (Begin guardID)

isSleep :: Event -> Bool
isSleep (Sleep _) = True
isSleep _         = False

glob :: (Ord a, Ord b) => ((a, b) -> (a, b) -> (a, b)) -> [(a, b)] -> [(a, b)]
glob f = map (reduce f) . groupBy ((==) `on` fst) . sort

process :: [Event] -> [(Event, [(Minute, Int)])]
process events = glob f [(last b, process' s) | [b, s] <- chunksOf 2 . groupBy ((==) `on` isSleep) $ events]
  where    
    process' sleeps = [(m, 1) | [Sleep a, Sleep b] <- chunksOf 2 sleeps, m <- [a..b-1]]
    f (b1, s1) (_, s2) = (b1, s1 ++ s2)

modeMinute :: [(Minute, Int)] -> (Minute, Int)
modeMinute = maximumBy (compare `on` snd) . glob f 
  where
    f (a, b) (_, c) = (a, b + c)

solve1 :: [(Event, [(Minute, Int)])] -> Int
solve1 shifts = 
  let (Begin sleepiest, minutes) = maximumBy (compare `on` length . snd) shifts
      (minute, _) = modeMinute minutes
  in  sleepiest * minute

solve2 :: [(Event, [(Minute, Int)])] -> Int
solve2 shifts = 
  let ((_, minute), Begin sleepiest) = maximum [((f, m), b) | (b, modeMinute -> (m, f)) <- shifts]
  in sleepiest * minute

main :: IO ()
main = do
  input <- sort . lines <$> readFile "04.txt"
  let shifts = process . mapMaybe parseLine $ input
  print $ solve1 shifts
  print $ solve2 shifts