From af70adae9b90e29d42fb10e32d0cfd040bd4e354 Mon Sep 17 00:00:00 2001 From: Neil Smith Date: Mon, 2 Dec 2019 11:18:35 +0000 Subject: [PATCH] Done day 2 Done day 2 --- advent02/package.yaml | 61 +++++++++++++++ advent02/src/advent02.hs | 122 +++++++++++++++++++++++++++++ data/advent02.txt | 1 + problems/day02.html | 165 +++++++++++++++++++++++++++++++++++++++ stack.yaml | 1 + 5 files changed, 350 insertions(+) create mode 100644 advent02/package.yaml create mode 100644 advent02/src/advent02.hs create mode 100644 data/advent02.txt create mode 100644 problems/day02.html diff --git a/advent02/package.yaml b/advent02/package.yaml new file mode 100644 index 0000000..e77a633 --- /dev/null +++ b/advent02/package.yaml @@ -0,0 +1,61 @@ +# This YAML file describes your package. Stack will automatically generate a +# Cabal file when you run `stack build`. See the hpack website for help with +# this file: . + +name: advent02 +synopsis: Advent of Code +version: '0.0.1' + +default-extensions: +- AllowAmbiguousTypes +- ApplicativeDo +- BangPatterns +- BlockArguments +- DataKinds +- DeriveFoldable +- DeriveFunctor +- DeriveGeneric +- DeriveTraversable +- EmptyCase +- FlexibleContexts +- FlexibleInstances +- FunctionalDependencies +- GADTs +- GeneralizedNewtypeDeriving +- ImplicitParams +- KindSignatures +- LambdaCase +- MonadComprehensions +- MonoLocalBinds +- MultiParamTypeClasses +- MultiWayIf +- NegativeLiterals +- NumDecimals +- OverloadedLists +- OverloadedStrings +- PartialTypeSignatures +- PatternGuards +- PatternSynonyms +- PolyKinds +- RankNTypes +- RecordWildCards +- ScopedTypeVariables +- TemplateHaskell +- TransformListComp +- TupleSections +- TypeApplications +- TypeInType +- TypeOperators +- ViewPatterns + + +executables: + advent02: + main: advent02.hs + source-dirs: src + dependencies: + - base >= 2 && < 6 + - text + - megaparsec + - containers + - mtl diff --git a/advent02/src/advent02.hs b/advent02/src/advent02.hs new file mode 100644 index 0000000..6eddc0a --- /dev/null +++ b/advent02/src/advent02.hs @@ -0,0 +1,122 @@ +-- Some code taken from [AoC 2017 day 5](https://adventofcode.com/2017/day/5), +-- and some from [AoC 2018 day 21](https://adventofcode.com/2018/day/21) + +import Data.Text (Text) +import qualified Data.Text.IO as TIO + +import Data.Void (Void) + +import Text.Megaparsec hiding (State) +import Text.Megaparsec.Char +import qualified Text.Megaparsec.Char.Lexer as L +import qualified Control.Applicative as CA + +import Control.Monad (unless) +import Control.Monad.State.Strict + +import qualified Data.IntMap.Strict as M +import Data.IntMap.Strict ((!)) + +type Memory = M.IntMap Int + +data Machine = Machine { _memory :: Memory + , _ip :: Int + } + deriving (Show, Eq) + +type ProgrammedMachine = State Machine () + + +main :: IO () +main = do + text <- TIO.readFile "data/advent02.txt" + let mem = successfulParse text + let machine = makeMachine mem + print $ part1 machine + print $ part2 machine + + +-- part1 machine = (_memory $ execState runAll machine1202)!0 +-- where machine1202 = machine { _memory = M.insert 1 12 $ M.insert 2 2 $ _memory machine } + + +part1 = nounVerbResult 12 2 + +part2Target = 19690720 + +part2 machine = noun * 100 + verb + where (noun, verb) = head $ [(n, v) | n <- [0..99], v <- [0..99], + nounVerbResult n v machine == part2Target ] + + +makeMachine :: [Int] -> Machine +makeMachine memory = Machine {_ip = 0, _memory = M.fromList $ zip [0..] memory} + +nounVerbResult :: Int -> Int -> Machine -> Int +nounVerbResult noun verb machine = machineOutput nvMachine + where nvMachine0 = machineNounVerb machine noun verb + nvMachine = execState runAll nvMachine0 + +machineNounVerb :: Machine -> Int -> Int -> Machine +machineNounVerb machine noun verb = machine { _memory = M.insert 1 noun $ M.insert 2 verb $ _memory machine } + +machineOutput :: Machine -> Int +machineOutput machine = (_memory machine)!0 + + +runAll :: ProgrammedMachine +runAll = do m0 <- get + unless (lkup (_ip m0) (_memory m0) == 99) + do runStep + runAll + +runStep :: ProgrammedMachine +runStep = + do m0 <- get + let mem = _memory m0 + let ip = _ip m0 + let (mem', ip') = perform (mem!ip) ip mem + put m0 {_ip = ip', _memory = mem'} + +perform :: Int -> Int -> Memory -> (Memory, Int) +perform 1 ip mem = (iInsert (ip + 3) (a + b) mem, ip + 4) + where a = mem!>(ip + 1) + b = mem!>(ip + 2) +perform 2 ip mem = (iInsert (ip + 3) (a * b) mem, ip + 4) + where a = mem!>(ip + 1) + b = mem!>(ip + 2) + + +-- Some IntMap utility functions, for syntactic sugar + +-- prefix version of (!) +lkup k m = m!k + +-- indirect lookup +(!>) m k = m!(m!k) + +-- indirect insert +iInsert k v m = M.insert (m!k) v m + + + +-- Parse the input file +type Parser = Parsec Void Text + +sc :: Parser () +sc = L.space (skipSome spaceChar) CA.empty CA.empty +-- sc = L.space (skipSome (char ' ')) CA.empty CA.empty + +lexeme = L.lexeme sc +integer = lexeme L.decimal +-- signedInteger = L.signed sc integer +symb = L.symbol sc +comma = symb "," + +memoryP = integer `sepBy` comma + +successfulParse :: Text -> [Int] +successfulParse input = + case parse memoryP "input" input of + Left _err -> [] -- TIO.putStr $ T.pack $ parseErrorPretty err + Right memory -> memory \ No newline at end of file diff --git a/data/advent02.txt b/data/advent02.txt new file mode 100644 index 0000000..3f2eaef --- /dev/null +++ b/data/advent02.txt @@ -0,0 +1 @@ +1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,9,19,1,5,19,23,1,6,23,27,1,27,10,31,1,31,5,35,2,10,35,39,1,9,39,43,1,43,5,47,1,47,6,51,2,51,6,55,1,13,55,59,2,6,59,63,1,63,5,67,2,10,67,71,1,9,71,75,1,75,13,79,1,10,79,83,2,83,13,87,1,87,6,91,1,5,91,95,2,95,9,99,1,5,99,103,1,103,6,107,2,107,13,111,1,111,10,115,2,10,115,119,1,9,119,123,1,123,9,127,1,13,127,131,2,10,131,135,1,135,5,139,1,2,139,143,1,143,5,0,99,2,0,14,0 \ No newline at end of file diff --git a/problems/day02.html b/problems/day02.html new file mode 100644 index 0000000..00749d5 --- /dev/null +++ b/problems/day02.html @@ -0,0 +1,165 @@ + + + + +Day 2 - Advent of Code 2019 + + + + + + + +

Advent of Code

Neil Smith (AoC++) 4*

  0.0.0.0:2019

+ + + +
+

--- Day 2: 1202 Program Alarm ---

On the way to your gravity assist around the Moon, your ship computer beeps angrily about a "1202 program alarm". On the radio, an Elf is already explaining how to handle the situation: "Don't worry, that's perfectly norma--" The ship computer bursts into flames.

+

You notify the Elves that the computer's magic smoke seems to have escaped. "That computer ran Intcode programs like the gravity assist program it was working on; surely there are enough spare parts up there to build a new Intcode computer!"

+

An Intcode program is a list of integers separated by commas (like 1,0,0,3,99). To run one, start by looking at the first integer (called position 0). Here, you will find an opcode - either 1, 2, or 99. The opcode indicates what to do; for example, 99 means that the program is finished and should immediately halt. Encountering an unknown opcode means something went wrong.

+

Opcode 1 adds together numbers read from two positions and stores the result in a third position. The three integers immediately after the opcode tell you these three positions - the first two indicate the positions from which you should read the input values, and the third indicates the position at which the output should be stored.

+

For example, if your Intcode computer encounters 1,10,20,30, it should read the values at positions 10 and 20, add those values, and then overwrite the value at position 30 with their sum.

+

Opcode 2 works exactly like opcode 1, except it multiplies the two inputs instead of adding them. Again, the three integers after the opcode indicate where the inputs and outputs are, not their values.

+

Once you're done processing an opcode, move to the next one by stepping forward 4 positions.

+

For example, suppose you have the following program:

+
1,9,10,3,2,3,11,0,99,30,40,50
+

For the purposes of illustration, here is the same program split into multiple lines:

+
1,9,10,3,
+2,3,11,0,
+99,
+30,40,50
+
+

The first four integers, 1,9,10,3, are at positions 0, 1, 2, and 3. Together, they represent the first opcode (1, addition), the positions of the two inputs (9 and 10), and the position of the output (3). To handle this opcode, you first need to get the values at the input positions: position 9 contains 30, and position 10 contains 40. Add these numbers together to get 70. Then, store this value at the output position; here, the output position (3) is at position 3, so it overwrites itself. Afterward, the program looks like this:

+
1,9,10,70,
+2,3,11,0,
+99,
+30,40,50
+
+

Step forward 4 positions to reach the next opcode, 2. This opcode works just like the previous, but it multiplies instead of adding. The inputs are at positions 3 and 11; these positions contain 70 and 50 respectively. Multiplying these produces 3500; this is stored at position 0:

+
3500,9,10,70,
+2,3,11,0,
+99,
+30,40,50
+
+

Stepping forward 4 more positions arrives at opcode 99, halting the program.

+

Here are the initial and final states of a few more small programs:

+
    +
  • 1,0,0,0,99 becomes 2,0,0,0,99 (1 + 1 = 2).
  • +
  • 2,3,0,3,99 becomes 2,3,0,6,99 (3 * 2 = 6).
  • +
  • 2,4,4,5,99,0 becomes 2,4,4,5,99,9801 (99 * 99 = 9801).
  • +
  • 1,1,1,4,99,5,6,0,99 becomes 30,1,1,4,2,5,6,0,99.
  • +
+

Once you have a working computer, the first step is to restore the gravity assist program (your puzzle input) to the "1202 program alarm" state it had just before the last computer caught fire. To do this, before running the program, replace position 1 with the value 12 and replace position 2 with the value 2. What value is left at position 0 after the program halts?

+
+

Your puzzle answer was 3562672.

--- Part Two ---

"Good, the new computer seems to be working correctly! Keep it nearby during this mission - you'll probably use it again. Real Intcode computers support many more features than your new one, but we'll let you know what they are as you need them."

+

"However, your current priority should be to complete your gravity assist around the Moon. For this mission to succeed, we should settle on some terminology for the parts you've already built."

+

Intcode programs are given as a list of integers; these values are used as the initial state for the computer's memory. When you run an Intcode program, make sure to start by initializing memory to the program's values. A position in memory is called an address (for example, the first value in memory is at "address 0").

+

Opcodes (like 1, 2, or 99) mark the beginning of an instruction. The values used immediately after an opcode, if any, are called the instruction's parameters. For example, in the instruction 1,2,3,4, 1 is the opcode; 2, 3, and 4 are the parameters. The instruction 99 contains only an opcode and has no parameters.

+

The address of the current instruction is called the instruction pointer; it starts at 0. After an instruction finishes, the instruction pointer increases by the number of values in the instruction; until you add more instructions to the computer, this is always 4 (1 opcode + 3 parameters) for the add and multiply instructions. (The halt instruction would increase the instruction pointer by 1, but it halts the program instead.)

+

"With terminology out of the way, we're ready to proceed. To complete the gravity assist, you need to determine what pair of inputs produces the output 19690720."

+

The inputs should still be provided to the program by replacing the values at addresses 1 and 2, just like before. In this program, the value placed in address 1 is called the noun, and the value placed in address 2 is called the verb. Each of the two input values will be between 0 and 99, inclusive.

+

Once the program has halted, its output is available at address 0, also just like before. Each time you try a pair of inputs, make sure you first reset the computer's memory to the values in the program (your puzzle input) - in other words, don't reuse memory from a previous attempt.

+

Find the input noun and verb that cause the program to produce the output 19690720. What is 100 * noun + verb? (For example, if noun=12 and verb=2, the answer would be 1202.)

+
+

Your puzzle answer was 8250.

Both parts of this puzzle are complete! They provide two gold stars: **

+

At this point, you should return to your Advent calendar and try another puzzle.

+

If you still want to see it, you can get your puzzle input.

+

You can also this puzzle.

+
+ + + + + + \ No newline at end of file diff --git a/stack.yaml b/stack.yaml index 115ecb8..9de915b 100644 --- a/stack.yaml +++ b/stack.yaml @@ -38,6 +38,7 @@ ghc-options: packages: # - . - advent01 +- advent02 # Dependency packages to be pulled from upstream that are not in the resolver. -- 2.34.1