Advent of Code, Day 2

In the 2nd day of Advent of Code, the task is to interpret “Intcode” programs.

Quoted from AoC:

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.

The opcodes are:

  • 1 - Add
  • 2 - Multiply
  • 99 - Halt

Here’s my solution in Haskell:

In the eval function, you might notice that I don’t check if the indices are within the bounds of the vector. Wont this blow up when we get to the end of the intcode? Nope.

Haskell is a lazy language, it doesn’t evaluate thing until it’s needed. And when he program gets to a Halt (99), it doesn’t need the other stuff (v1Pos, v2Pos etc), and thus it doesn’t evaluate them.

Pretty cool.

I also did the meat of the problem in Clojure: