From 7fe5f45a60fff53d966cb80916c17fb165c40c59 Mon Sep 17 00:00:00 2001 From: Jonathan Chan Date: Sun, 9 Dec 2018 00:28:33 -0800 Subject: [PATCH] Day 09. --- README.md | 2 +- app/Main.hs | 2 +- src/Day09.hs | 40 ++++++++++++++++++++++++++++++++++++++-- 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8625e20..d1eccd4 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ To arrive at [⟨ortho|normal⟩](https://hilb.ert.space) as December comes. | 05 | ~ 1 | | 06 | ~ 3 | | 07 | ~ 1 | -| 08 | | +| 08 | ~ 6.5 | | 09 | | | 10 | | | 11 | | diff --git a/app/Main.hs b/app/Main.hs index 3210c94..e48b8d4 100644 --- a/app/Main.hs +++ b/app/Main.hs @@ -30,4 +30,4 @@ import qualified Day24 import qualified Day25 main :: IO () -main = Day07.main +main = Day09.main diff --git a/src/Day09.hs b/src/Day09.hs index c218e82..e87ea8b 100644 --- a/src/Day09.hs +++ b/src/Day09.hs @@ -1,6 +1,42 @@ +{-# LANGUAGE BangPatterns #-} + module Day09 (main) where +import Data.IntMap (IntMap, empty, insertWith) +import Data.Sequence (Seq((:<|)), fromList, (><), (<|)) +import qualified Data.Sequence as S (length, drop, take) + +players = 411 +lastMarble = 7105800 +infix 5 % +(%) = mod + +-- (scoreboard, marbles, marble, player) +type State = (Scoreboard, Marbles, Int, Int) +type Scoreboard = IntMap Int +type Marbles = Seq Int + +-- pop from the front and push in the back n marbles +spin :: Int -> Marbles -> Marbles +spin n m = S.drop n m >< S.take n m + +-- pop from the back and push in the front n marbles +unspin :: Int -> Marbles -> Marbles +unspin n m = S.drop (S.length m - n) m >< S.take (S.length m - n) m + +part1 :: State -> Int +part1 (scores, marbles, m, p) + | nextMarble == lastMarble = maximum scores + | nextMarble % 23 == 0 = + let !(m:<|nextMarbles) = unspin 7 marbles + nextScores = insertWith (+) nextPlayer (nextMarble + m) scores + in part1 (nextScores, nextMarbles, nextMarble, nextPlayer) + | otherwise = + let !nextMarbles = nextMarble <| spin 2 marbles + in part1 (scores, nextMarbles, nextMarble, nextPlayer) + where nextMarble = m + 1 + nextPlayer = (p % players) + 1 + main :: IO () main = do - input <- readFile "input/09.txt" - print input \ No newline at end of file + print $ part1 (empty, fromList [1, 0], 1, 1) \ No newline at end of file