Done day 2
authorNeil Smith <neil.git@njae.me.uk>
Mon, 2 Dec 2019 11:18:35 +0000 (11:18 +0000)
committerNeil Smith <neil.git@njae.me.uk>
Mon, 2 Dec 2019 11:18:49 +0000 (11:18 +0000)
Done day 2

advent02/package.yaml [new file with mode: 0644]
advent02/src/advent02.hs [new file with mode: 0644]
data/advent02.txt [new file with mode: 0644]
problems/day02.html [new file with mode: 0644]
stack.yaml

diff --git a/advent02/package.yaml b/advent02/package.yaml
new file mode 100644 (file)
index 0000000..e77a633
--- /dev/null
@@ -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: <https://github.com/sol/hpack>.
+
+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 (file)
index 0000000..6eddc0a
--- /dev/null
@@ -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 (file)
index 0000000..3f2eaef
--- /dev/null
@@ -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 (file)
index 0000000..00749d5
--- /dev/null
@@ -0,0 +1,165 @@
+<!DOCTYPE html>
+<html lang="en-us">
+<head>
+<meta charset="utf-8"/>
+<title>Day 2 - Advent of Code 2019</title>
+<!--[if lt IE 9]><script src="/static/html5.js"></script><![endif]-->
+<link href='//fonts.googleapis.com/css?family=Source+Code+Pro:300&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
+<link rel="stylesheet" type="text/css" href="/static/style.css?22"/>
+<link rel="stylesheet alternate" type="text/css" href="/static/highcontrast.css?0" title="High Contrast"/>
+<link rel="shortcut icon" href="/favicon.png"/>
+</head><!--
+
+
+
+
+Oh, hello!  Funny seeing you here.
+
+I appreciate your enthusiasm, but you aren't going to find much down here.
+There certainly aren't clues to any of the puzzles.  The best surprises don't
+even appear in the source until you unlock them for real.
+
+Please be careful with automated requests; I'm not a massive company, and I can
+only take so much traffic.  Please be considerate so that everyone gets to play.
+
+If you're curious about how Advent of Code works, it's running on some custom
+Perl code. Other than a few integrations (auth, analytics, ads, social media),
+I built the whole thing myself, including the design, animations, prose, and
+all of the puzzles.
+
+The puzzles are most of the work; preparing a new calendar and a new set of
+puzzles each year takes all of my free time for 4-5 months. A lot of effort
+went into building this thing - I hope you're enjoying playing it as much as I
+enjoyed making it for you!
+
+If you'd like to hang out, I'm @ericwastl on Twitter.
+
+- Eric Wastl
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+-->
+<body>
+<header><div><h1 class="title-global"><a href="/">Advent of Code</a></h1><nav><ul><li><a href="/2019/about">[About]</a></li><li><a href="/2019/events">[Events]</a></li><li><a href="https://teespring.com/adventofcode-2019" target="_blank">[Shop]</a></li><li><a href="/2019/settings">[Settings]</a></li><li><a href="/2019/auth/logout">[Log Out]</a></li></ul></nav><div class="user">Neil Smith <a href="/2019/support" class="supporter-badge" title="Advent of Code Supporter">(AoC++)</a> <span class="star-count">4*</span></div></div><div><h1 class="title-event">&nbsp;&nbsp;<span class="title-event-wrap">0.0.0.0:</span><a href="/2019">2019</a><span class="title-event-wrap"></span></h1><nav><ul><li><a href="/2019">[Calendar]</a></li><li><a href="/2019/support">[AoC++]</a></li><li><a href="/2019/sponsors">[Sponsors]</a></li><li><a href="/2019/leaderboard">[Leaderboard]</a></li><li><a href="/2019/stats">[Stats]</a></li></ul></nav></div></header>
+
+<div id="sidebar">
+<div id="sponsor"><div class="quiet">Our <a href="/2019/sponsors">sponsors</a> help make Advent of Code possible:</div><div class="sponsor"><a href="https://www.codethink.co.uk/" target="_blank" onclick="if(ga)ga('send','event','sponsor','sidebar',this.href);" rel="noopener">Codethink Ltd.</a> - Codethink is a software services company, expert in the use of Open Source technologies for systems software engineering.</div></div>
+</div><!--/sidebar-->
+
+<main>
+<article class="day-desc"><h2>--- Day 2: 1202 Program Alarm ---</h2><p>On the way to your <a href="https://en.wikipedia.org/wiki/Gravity_assist">gravity assist</a> around the Moon, your ship computer beeps angrily about a "<a href="https://www.hq.nasa.gov/alsj/a11/a11.landing.html#1023832">1202 program alarm</a>". On the radio, an Elf is already explaining how to handle the situation: "Don't worry, that's perfectly norma--" The ship computer <a href="https://en.wikipedia.org/wiki/Halt_and_Catch_Fire">bursts into flames</a>.</p>
+<p>You notify the Elves that the computer's <a href="https://en.wikipedia.org/wiki/Magic_smoke">magic smoke</a> seems to have <span title="Looks like SOMEONE forgot to change the switch to 'more magic'.">escaped</span>. "That computer ran <em>Intcode</em> programs like the gravity assist program it was working on; surely there are enough spare parts up there to build a new Intcode computer!"</p>
+<p>An Intcode program is a list of <a href="https://en.wikipedia.org/wiki/Integer">integers</a> separated by commas (like <code>1,0,0,3,99</code>).  To run one, start by looking at the first integer (called position <code>0</code>). Here, you will find an <em>opcode</em> - either <code>1</code>, <code>2</code>, or <code>99</code>. The opcode indicates what to do; for example, <code>99</code> means that the program is finished and should immediately halt. Encountering an unknown opcode means something went wrong.</p>
+<p>Opcode <code>1</code> <em>adds</em> together numbers read from two positions and stores the result in a third position. The three integers <em>immediately after</em> the opcode tell you these three positions - the first two indicate the <em>positions</em> from which you should read the input values, and the third indicates the <em>position</em> at which the output should be stored.</p>
+<p>For example, if your Intcode computer encounters <code>1,10,20,30</code>, it should read the values at positions <code>10</code> and <code>20</code>, add those values, and then overwrite the value at position <code>30</code> with their sum.</p>
+<p>Opcode <code>2</code> works exactly like opcode <code>1</code>, except it <em>multiplies</em> the two inputs instead of adding them. Again, the three integers after the opcode indicate <em>where</em> the inputs and outputs are, not their values.</p>
+<p>Once you're done processing an opcode, <em>move to the next one</em> by stepping forward <code>4</code> positions.</p>
+<p>For example, suppose you have the following program:</p>
+<pre><code>1,9,10,3,2,3,11,0,99,30,40,50</code></pre>
+<p>For the purposes of illustration, here is the same program split into multiple lines:</p>
+<pre><code>1,9,10,3,
+2,3,11,0,
+99,
+30,40,50
+</code></pre>
+<p>The first four integers, <code>1,9,10,3</code>, are at positions <code>0</code>, <code>1</code>, <code>2</code>, and <code>3</code>. Together, they represent the first opcode (<code>1</code>, addition), the positions of the two inputs (<code>9</code> and <code>10</code>), and the position of the output (<code>3</code>).  To handle this opcode, you first need to get the values at the input positions: position <code>9</code> contains <code>30</code>, and position <code>10</code> contains <code>40</code>.  <em>Add</em> these numbers together to get <code>70</code>.  Then, store this value at the output position; here, the output position (<code>3</code>) is <em>at</em> position <code>3</code>, so it overwrites itself.  Afterward, the program looks like this:</p>
+<pre><code>1,9,10,<em>70</em>,
+2,3,11,0,
+99,
+30,40,50
+</code></pre>
+<p>Step forward <code>4</code> positions to reach the next opcode, <code>2</code>. This opcode works just like the previous, but it multiplies instead of adding.  The inputs are at positions <code>3</code> and <code>11</code>; these positions contain <code>70</code> and <code>50</code> respectively. Multiplying these produces <code>3500</code>; this is stored at position <code>0</code>:</p>
+<pre><code><em>3500</em>,9,10,70,
+2,3,11,0,
+99,
+30,40,50
+</code></pre>
+<p>Stepping forward <code>4</code> more positions arrives at opcode <code>99</code>, halting the program.</p>
+<p>Here are the initial and final states of a few more small programs:</p>
+<ul>
+<li><code>1,0,0,0,99</code> becomes <code><em>2</em>,0,0,0,99</code> (<code>1 + 1 = 2</code>).</li>
+<li><code>2,3,0,3,99</code> becomes <code>2,3,0,<em>6</em>,99</code> (<code>3 * 2 = 6</code>).</li>
+<li><code>2,4,4,5,99,0</code> becomes <code>2,4,4,5,99,<em>9801</em></code> (<code>99 * 99 = 9801</code>).</li>
+<li><code>1,1,1,4,99,5,6,0,99</code> becomes <code><em>30</em>,1,1,4,<em>2</em>,5,6,0,99</code>.</li>
+</ul>
+<p>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, <em>before running the program</em>, replace position <code>1</code> with the value <code>12</code> and replace position <code>2</code> with the value <code>2</code>. <em>What value is left at position <code>0</code></em> after the program halts?</p>
+</article>
+<p>Your puzzle answer was <code>3562672</code>.</p><article class="day-desc"><h2 id="part2">--- Part Two ---</h2><p>"Good, the new computer seems to be working correctly!  <em>Keep it nearby</em> 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."</p>
+<p>"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."</p>
+<p>Intcode programs are given as a list of integers; these values are used as the initial state for the computer's <em>memory</em>. 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 <em>address</em> (for example, the first value in memory is at "address 0").</p>
+<p>Opcodes (like <code>1</code>, <code>2</code>, or <code>99</code>) mark the beginning of an <em>instruction</em>.  The values used immediately after an opcode, if any, are called the instruction's <em>parameters</em>.  For example, in the instruction <code>1,2,3,4</code>, <code>1</code> is the opcode; <code>2</code>, <code>3</code>, and <code>4</code> are the parameters. The instruction <code>99</code> contains only an opcode and has no parameters.</p>
+<p>The address of the current instruction is called the <em>instruction pointer</em>; it starts at <code>0</code>.  After an instruction finishes, the instruction pointer increases by <em>the number of values in the instruction</em>; until you add more instructions to the computer, this is always <code>4</code> (<code>1</code> opcode + <code>3</code> parameters) for the add and multiply instructions. (The halt instruction would increase the instruction pointer by <code>1</code>, but it halts the program instead.)</p>
+<p>"With terminology out of the way, we're ready to proceed. To complete the gravity assist, you need to <em>determine what pair of inputs produces the output <code>19690720</code></em>."</p>
+<p>The inputs should still be provided to the program by replacing the values at addresses <code>1</code> and <code>2</code>, just like before.  In this program, the value placed in address <code>1</code> is called the <em>noun</em>, and the value placed in address <code>2</code> is called the <em>verb</em>.   Each of the two input values will be between <code>0</code> and <code>99</code>, inclusive.</p>
+<p>Once the program has halted, its output is available at address <code>0</code>, also just like before. Each time you try a pair of inputs, make sure you first <em>reset the computer's memory to the values in the program</em> (your puzzle input) - in other words, don't reuse memory from a previous attempt.</p>
+<p>Find the input <em>noun</em> and <em>verb</em> that cause the program to produce the output <code>19690720</code>. <em>What is <code>100 * noun + verb</code>?</em> (For example, if <code>noun=12</code> and <code>verb=2</code>, the answer would be <code>1202</code>.)</p>
+</article>
+<p>Your puzzle answer was <code>8250</code>.</p><p class="day-success">Both parts of this puzzle are complete! They provide two gold stars: **</p>
+<p>At this point, you should <a href="/2019">return to your Advent calendar</a> and try another puzzle.</p>
+<p>If you still want to see it, you can <a href="2/input" target="_blank">get your puzzle input</a>.</p>
+<p>You can also <span class="share">[Share<span class="share-content">on
+  <a href="https://twitter.com/intent/tweet?text=I%27ve+completed+%221202+Program+Alarm%22+%2D+Day+2+%2D+Advent+of+Code+2019&amp;url=https%3A%2F%2Fadventofcode%2Ecom%2F2019%2Fday%2F2&amp;related=ericwastl&amp;hashtags=AdventOfCode" target="_blank">Twitter</a>
+  <a href="http://www.reddit.com/submit?url=https%3A%2F%2Fadventofcode%2Ecom%2F2019%2Fday%2F2&amp;title=I%27ve+completed+%221202+Program+Alarm%22+%2D+Day+2+%2D+Advent+of+Code+2019" target="_blank">Reddit</a
+></span>]</span> this puzzle.</p>
+</main>
+
+<!-- ga -->
+<script>
+(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
+(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
+m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
+})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
+ga('create', 'UA-69522494-1', 'auto');
+ga('set', 'anonymizeIp', true);
+ga('send', 'pageview');
+</script>
+<!-- /ga -->
+</body>
+</html>
\ No newline at end of file
index 115ecb82eb23532c9c8cc65e9f62d34838b97d12..9de915b587741b893b8ffa2a7865cfa4894f4456 100644 (file)
@@ -38,6 +38,7 @@ ghc-options:
 packages:
 # - .
 - advent01
+- advent02
 
 
 # Dependency packages to be pulled from upstream that are not in the resolver.