Day 2 of Advent of Code 2019 was also pretty straightforward and once again I wrote my solution in Clojure but in order to talk about this from a teacher's point of view, we'll look at a Python solution.
At its core, this is a simulation problem - read the data into an array or list and write a program to run through the steps. At first I was hoping that the solution would consume the data - that is, once you read past an instruction you don't go back to it. If it was, I was going to try to write some clever reduce. It wasn't. In this problem, any instruction could affect any part of the data set. This means you have to keep the entire data set in memory and preferably in a random access structure like an array.
Step 1 is to read in the data and convert it into a list of integers.
If you don't know comprehensions you can just do something like this:
Now we just have to run the simulation:
The most likely source of error here is forgetting to change the
program in lines 18 and 19 as
specified in the question. The other likely error is forgetting to do
the two level indirection in lines 7 and 8. That is writing
program[ip+2] by mistake. Truth be told, I made
both of these mistakes but I didn't find them to be "interesting"
The interesting part of this program is part 2 where instead of
2 you have to try
values between 0 and 99 inclusive for each entry until you find a
This is a great platform to talk about memory. The problem refers to
the values you put into
program as nouns and
verbs. The issue is that every time you run your program for a
specific noun verb combination you change the array (list)
representing your program. If you don't reset the array to its
original contents before the next run, the next run will be working
off of new values and therefore give you incorrect results.
This is a great platform for discussion. Students usually start with pass by value semantics so passing a list to a function and then having the list change can seem weird even though it can still be pass by value:
Here's a finished solution:
Note that in line 30 we copy over the original data for each noun,verb combo. also note the list comprehension in line 35 to find the final answer.
One last potential error point is notice that we had to add the array copy in line 20. Otherwise part1 will change the data and if we run it before part2 we won't get the correct result.
So there it is. Another nice problem and even though it's a straightforward problem, there's still some interesting meat to discuss with your students.
Tomorrow, snowstorm notwithstanding, I'll be heading up to Albany for the remainder of the week so might not be able to get to day 3 and beyond until Friday so who knows if I'll post any more of these write ups.