From b476cb67744c79c606101017421ba7cff7bf16db Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Tue, 15 Dec 2020 14:32:57 +0100 Subject: [PATCH] Add 2020 day 15 --- haskellAoC/inputs/2020/15 | 1 + haskellAoC/src/Y2020/Day15.hs | 41 +++++++++++++++++++++++++++++++++++ haskellAoC/src/Y2020/Days.hs | 2 ++ 3 files changed, 44 insertions(+) create mode 100644 haskellAoC/inputs/2020/15 create mode 100644 haskellAoC/src/Y2020/Day15.hs diff --git a/haskellAoC/inputs/2020/15 b/haskellAoC/inputs/2020/15 new file mode 100644 index 0000000..fe5b9c2 --- /dev/null +++ b/haskellAoC/inputs/2020/15 @@ -0,0 +1 @@ +9,6,0,10,18,2,1 \ No newline at end of file diff --git a/haskellAoC/src/Y2020/Day15.hs b/haskellAoC/src/Y2020/Day15.hs new file mode 100644 index 0000000..be008a5 --- /dev/null +++ b/haskellAoC/src/Y2020/Day15.hs @@ -0,0 +1,41 @@ +module Y2020.Day15 (y20day15) where + +import qualified Data.IntMap as IM +import Data.List.Split + +data State = State { + turn :: Int + , prevOffset :: IM.IntMap Int + , memory :: [Int] + } deriving (Show) + +playGame :: State -> State +playGame (State t prev xs@(x:_)) = + let newOffsets = IM.insert x (t - 1) prev + newTurn = (t + 1) + newState mem = State newTurn newOffsets mem + in + case x `IM.lookup` prev of + Nothing -> newState (0:xs) + Just n -> newState (y:xs) + where y = (t - 1) - n + +playNtimes :: Int -> State -> State +playNtimes n input + | (turn input) == n = input + | otherwise = playNtimes n $ playGame input + +memToOffsets :: Int -> [Int] -> [(Int, Int)] +memToOffsets _ [] = [] +memToOffsets ofs (h:t) = (h,ofs):(memToOffsets (ofs+1) t) + +y20day15 :: [String] -> (String, String) +y20day15 (input:_) = (part1, part2) + where part1 = show $ head $ memory $ playNtimes (2020 + 1) initialState + part2 = show $ head $ memory $ playNtimes (30000000 + 1) initialState + + initialState = State initialTurn initialPrevious initialMemory + + initialTurn = (1 + length initialMemory) + initialPrevious = (IM.fromList $ memToOffsets 1 $ reverse $ tail $ initialMemory) + initialMemory = reverse $ map read $ splitOn "," input :: [Int] diff --git a/haskellAoC/src/Y2020/Days.hs b/haskellAoC/src/Y2020/Days.hs index e14b565..af5b65d 100644 --- a/haskellAoC/src/Y2020/Days.hs +++ b/haskellAoC/src/Y2020/Days.hs @@ -14,6 +14,7 @@ import Y2020.Day11 import Y2020.Day12 import Y2020.Day13 import Y2020.Day14 +import Y2020.Day15 year2020 :: String -> [String] -> (String, String) year2020 "01" = y20day01 @@ -30,3 +31,4 @@ year2020 "11" = y20day11 year2020 "12" = y20day12 year2020 "13" = y20day13 year2020 "14" = y20day14 +year2020 "15" = y20day15