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!

38 Upvotes

340 comments sorted by

View all comments

1

u/misterboya Dec 04 '18

Partial Haskell solution that uses parser to read logs:

{-# LANGUAGE OverloadedStrings #-}

import Data.Attoparsec.ByteString.Char8 hiding (take, count)
import Data.ByteString.Char8 hiding (maximum, length, pack, head, count, take, foldl, putStrLn, map)
import Prelude hiding (getContents, count, lines)

import Data.Char
import Data.List (sort, sortBy, maximumBy)
import Control.Applicative
import qualified Data.Map.Strict as Map

data Event = ShiftStarts Integer | FallsAsleep | WakesUp deriving (Show)
data Log = Log Integer Integer Integer Integer Integer Event deriving (Show)

parseShiftStarts :: Parser Event
parseShiftStarts = do
  string "Guard"
  space
  char '#'
  guard <- decimal
  space
  string "begins"
  space
  string "shift"
  return $ ShiftStarts guard

parseWakesUp :: Parser Event
parseWakesUp = do
  string "wakes"
  space
  string "up"
  return $ WakesUp

parseFallsAsleep :: Parser Event
parseFallsAsleep = do
  string "falls"
  space
  string "asleep"
  return $ FallsAsleep

parseEvent :: Parser Event
parseEvent = parseFallsAsleep <|> parseWakesUp <|> parseShiftStarts

parseLog :: Parser Log
parseLog = do
  char '['
  year <- decimal
  char '-'
  month <- decimal
  char '-'
  day <- decimal
  space
  hour <- decimal
  char ':'
  minute <- decimal
  char ']'
  space
  event <- parseEvent
  return $ Log year month day hour minute event

parser input = parser' result'
  where
    parser' (Right a) = a
    result' = parseOnly parseLog input

solution :: [Log] -> Integer
solution cs = guard * minute
  where
    ...

main :: IO ()
main = do
   content <- getContents
   let
     toTuple (Log year month day hour minute _) = (year,month,day,hour,minute)
   putStrLn $ show $ solution $ sortBy (\a b -> compare (toTuple a) (toTuple b)) $ map (parser) $ lines content