Skip to content

Commit

Permalink
day4
Browse files Browse the repository at this point in the history
  • Loading branch information
ilya-bobyr committed Dec 19, 2019
1 parent 35ac405 commit 7a590d1
Show file tree
Hide file tree
Showing 6 changed files with 274 additions and 0 deletions.
30 changes: 30 additions & 0 deletions day4/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
Copyright Ilya Bobyr (c) 2018

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.

* Neither the name of Ilya Bobyr nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1 change: 1 addition & 0 deletions day4/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# day4
2 changes: 2 additions & 0 deletions day4/Setup.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import Distribution.Simple
main = defaultMain
25 changes: 25 additions & 0 deletions day4/day4.cabal
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: day4
version: 0.1.0.0
-- synopsis:
-- description:
homepage: https://github.com/ilya-bobyr/advent-of-code-2018/day4#readme
license: BSD3
license-file: LICENSE
author: Ilya Bobyr
maintainer: [email protected]
copyright: (c) 2018 Ilya Bobyr
category: Web
build-type: Simple
cabal-version: >=1.10
extra-source-files: README.md

executable day4
hs-source-dirs: src
main-is: Main.hs
default-language: Haskell2010
ghc-options: -O2 -fdiagnostics-color=always
build-depends: base >= 4.7 && < 5
, containers
, parsec
, sort
, time
152 changes: 152 additions & 0 deletions day4/src/Main.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
{-# LANGUAGE LambdaCase #-}

module Main where

import Prelude hiding (log)

import Data.Bits (setBit, popCount, testBit)
import Data.List (foldl', maximumBy, elemIndex)
import Data.Ord (comparing)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Sort (sortOn)
import Data.Word (Word64)
import Text.Parsec (parse)
import Text.Parsec.Prim (try, (<|>))
import Text.Parsec.Char (char, digit, space, spaces, string, newline)
import Text.Parsec.Combinator (many1, eof, sepEndBy)
import Text.Parsec.String (Parser)
import Text.Printf (printf, perror)

data LogEvent = BeginShift Int
| FallAsleep
| WakeUp
deriving (Show)

data LogDate = LogDate Int Int Int
deriving (Eq, Ord)

instance Show LogDate where
show (LogDate year month day) = printf "%d-%02d-%02d" year month day

data LogTime = LogTime Int Int
deriving (Eq, Ord)

instance Show LogTime where
show (LogTime hour minute) = printf "%02d:%02d" hour minute

data LogDateTime = LogDateTime LogDate LogTime
deriving (Eq, Ord)

instance Show LogDateTime where
show (LogDateTime date time) = show date ++ " " ++ show time

data LogEntry = LogEntry {
unLogDateTime :: LogDateTime,
unLogEvent :: LogEvent
}
deriving (Show)

logDateTime :: Int -> Int -> Int -> Int -> Int -> LogDateTime
logDateTime year month day hour minute =
LogDateTime (LogDate year month day) (LogTime hour minute)

rowParser :: Parser LogEntry
rowParser = do
_ <- char '['
year <- read <$> many1 digit :: Parser Int
_ <- char '-'
month <- read <$> many1 digit :: Parser Int
_ <- char '-'
day <- read <$> many1 digit :: Parser Int
_ <- space
hour <- read <$> many1 digit :: Parser Int
_ <- char ':'
minute <- read <$> many1 digit :: Parser Int
_ <- char ']'
spaces
event <- try (do _ <- string "Guard #"
gId <- read <$> many1 digit :: Parser Int
_ <- string " begins shift"
return $ BeginShift gId)
<|> try (do _ <- string "falls asleep"
return FallAsleep)
<|> try (do _ <- string "wakes up"
return WakeUp)
let datetime = logDateTime year month day hour minute
return $ LogEntry datetime event

inputParser :: Parser [LogEntry]
inputParser = do
allClaims <- rowParser `sepEndBy` newline
eof
return allClaims

data GuardState = Awake | Asleep

orderedEventsToStats :: [LogEntry] -> Map Int [Word64]
orderedEventsToStats (LogEntry _ (BeginShift firstGId) : events) =
let addLog gId log =
Map.alter (\case Nothing -> Just [log]
Just prev -> Just (log : prev)) gId

extendLog from to Asleep log | from < to =
extendLog (from + 1) to Asleep (log `setBit` from)
extendLog _ _ _ log = log

combine gId from state log [] res =
let log' = extendLog from 59 state log
in addLog gId log' res
combine gId from state log
(LogEntry _ (BeginShift newGId) : events') res =
let log' = extendLog from 59 state log
in combine newGId 0 Awake 0 events' (addLog gId log' res)
combine gId from state log
(LogEntry (LogDateTime _ (LogTime _ minute)) FallAsleep : events') res =
let log' = extendLog from minute state log
in combine gId minute Asleep log' events' res
combine gId from state log
(LogEntry (LogDateTime _ (LogTime _ minute)) WakeUp : events') res =
let log' = extendLog from minute state log
in combine gId minute Awake log' events' res

in combine firstGId 0 Awake 0 events Map.empty

orderedEventsToStats unexpected =
perror "Unexpected first log entry: %s" unexpected

perMinutStats :: [Word64] -> [Int]
perMinutStats logs =
let addLog res log =
map (\(i, r) -> if log `testBit` i then r + 1 else r)
$ zip [0..] res
in foldl' addLog (replicate 60 0) logs

strategy1 :: Map Int [Word64] -> Int
strategy1 stats =
let sleepAmounts = Map.map (foldl' (\a v -> a + popCount v) 0) stats
topSleeper = fst . maximumBy (comparing snd) $ Map.toList sleepAmounts
topSleeperStats = perMinutStats $ stats Map.! topSleeper
bestMinute =
fst . maximumBy (comparing snd) $ zip [0..] topSleeperStats
in topSleeper * bestMinute

strategy2 :: Map Int [Word64] -> Int
strategy2 stats =
let perMinute = Map.map perMinutStats stats
sameMinuteMax = Map.map maximum perMinute
(topSleeper, maxMinute) =
maximumBy (comparing snd) $ Map.toList sameMinuteMax
(Just bestMinute) = elemIndex maxMinute $ perMinute Map.! topSleeper
in topSleeper * bestMinute

main :: IO ()
main = do
input <- getContents
case parse inputParser "<input>" input of
Left errorText -> print errorText
Right events -> do
let orderedEvents = sortOn unLogDateTime events
stats = orderedEventsToStats orderedEvents
print $ strategy1 stats
print $ strategy2 stats
64 changes: 64 additions & 0 deletions day4/stack.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# This file was automatically generated by 'stack init'
#
# Some commonly used options have been documented as comments in this file.
# For advanced use and comprehensive documentation of the format, please see:
# https://docs.haskellstack.org/en/stable/yaml_configuration/

# Resolver to choose a 'specific' stackage snapshot or a compiler version.
# A snapshot resolver dictates the compiler version and the set of packages
# to be used for project dependencies. For example:
#
# resolver: lts-3.5
# resolver: nightly-2015-09-21
# resolver: ghc-7.10.2
#
# The location of a snapshot can be provided as a file or url. Stack assumes
# a snapshot provided as a file might change, whereas a url resource does not.
#
# resolver: ./custom-snapshot.yaml
# resolver: https://example.com/snapshots/2018-01-01.yaml
resolver: lts-12.21

# User packages to be built.
# Various formats can be used as shown in the example below.
#
# packages:
# - some-directory
# - https://example.com/foo/bar/baz-0.0.2.tar.gz
# - location:
# git: https://github.com/commercialhaskell/stack.git
# commit: e7b331f14bcffb8367cd58fbfc8b40ec7642100a
# - location: https://github.com/commercialhaskell/stack/commit/e7b331f14bcffb8367cd58fbfc8b40ec7642100a
# subdirs:
# - auto-update
# - wai
packages:
- .
# Dependency packages to be pulled from upstream that are not in the resolver
# using the same syntax as the packages field.
# (e.g., acme-missiles-0.3)
# extra-deps: []

# Override default flag values for local packages and extra-deps
# flags: {}

# Extra package databases containing global packages
# extra-package-dbs: []

# Control whether we use the GHC we find on the path
# system-ghc: true
#
# Require a specific version of stack, using version ranges
# require-stack-version: -any # Default
# require-stack-version: ">=1.9"
#
# Override the architecture used by stack, especially useful on Windows
# arch: i386
# arch: x86_64
#
# Extra directories used by stack for building
# extra-include-dirs: [/path/to/dir]
# extra-lib-dirs: [/path/to/dir]
#
# Allow a newer minor version of GHC than the snapshot specifies
# compiler-check: newer-minor

0 comments on commit 7a590d1

Please sign in to comment.