Advent of Code: Day 2
Just like clockwork, Day 2 opened precisely at midnight of Eastern Standard Time.
The Puzzle
The puzzle, called Dive, has an input file that contains a list of commands. Each command has a word and a value, which represent a movement and how much to move, respectively. The words can be: forward to increase forward (horizontal) position, down to increase depth, and up to decrease depth. For example, this input:
forward 5
down 5
forward 8
up 3
down 8
forward 2
tells us that, if you move according to these commands from your starting point, you will be 15 forward and 10 deep. And the puzzle expects you to give it the product of these two numbers (150 in this case).
Here’s my code to solve it:
file = open('input.txt')
lines = file.read().splitlines()
x = 0
depth = 0
for line in lines:
items = line.split()
command = items[0]
value = int(items[1])
match command:
case 'forward':
x += value
case 'down':
depth += value
case 'up':
depth -= value
print(x * depth)
After Part 1 was solved, Part 2 presented a new element: aim. Similar to Part 1, but it has some modifications:
down X
increases your aim byX
units.up X
decreases your aim byX
units.forward X
does two things:It increases your horizontal position by
X
units.It increases your depth by your aim multiplied by
X
.
So the code evolved:
file = open('input.txt')
lines = file.read().splitlines()
x = 0
depth = 0
aim = 0
for line in lines:
items = line.split()
command = items[0]
value = int(items[1])
match command:
case 'forward':
x += value
depth += aim * value
case 'down':
aim += value
case 'up':
aim -= value
print(x * depth)
Huge Community
Man does this Advent of Code have a huge community! It has a DJ performing live when the puzzle started. Day 2 has people visualizing the problems like this one here. Folks have formed clubs, private leaderboards, and thinktanks to brainstorm and solve these puzzles together.
I expect to last ‘til December 25. Do you?