Skip to content

Commit

Permalink
2021 d2: merge duplicated variable into one
Browse files Browse the repository at this point in the history
Fixes #11.
  • Loading branch information
mebeim committed Dec 4, 2021
1 parent 90d930a commit d7a3fa6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 20 deletions.
23 changes: 12 additions & 11 deletions 2021/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,28 +118,28 @@ change meaning. `down X`/`up X` now increase/decrease our *aim* by `X`, while
increase the depth by the current aim multiplied by `X`.

Nothing absurd. We can actually integrate this in the same loop we just wrote,
by creating two new variables for the aim and the new depth. Other than that,
it's just additions and multiplications.
by creating two new variables for the aim and the new depth. Since the aim is
actually updated exactly like the original depth, we can also cheap out on
variables and just add one ([thanks @NimVek for noticing][misc-issue-11]). Other
than that, it's just additions and multiplications.

```python
aim = horiz = depth1 = depth2 = 0
aim = horiz = depth = 0

for line in fin:
cmd, x = line.split()
x = int(x)

if cmd == 'down':
depth1 += x
aim += x
aim += x
elif cmd == 'up':
depth1 -= x
aim -= x
aim -= x
else:
horiz += x
depth2 += aim * x
horiz += x
depth += aim * x

answer1 = horiz * depth1
answer2 = horiz * depth2
answer1 = horiz * aim
answer2 = horiz * depth

print('Part 1:', answer1)
print('Part 2:', answer1)
Expand Down Expand Up @@ -644,3 +644,4 @@ a bingo game simulation is pretty fun!
[wiki-bingo]: https://en.wikipedia.org/wiki/Bingo_(American_version)

[misc-aoc-bingo]: https://www.reddit.com/r/adventofcode/comments/k3q7tr/
[misc-issue-11]: https://github.com/mebeim/aoc/issues/11
16 changes: 7 additions & 9 deletions 2021/solutions/day02.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,22 @@
advent.setup(2021, 2)
fin = advent.get_input()

aim = horiz = depth1 = depth2 = 0
aim = horiz = depth = 0

for line in fin:
cmd, x = line.split()
x = int(x)

if cmd == 'down':
depth1 += x
aim += x
aim += x
elif cmd == 'up':
depth1 -= x
aim -= x
aim -= x
else:
horiz += x
depth2 += aim * x
horiz += x
depth += aim * x

answer1 = horiz * depth1
answer2 = horiz * depth2
answer1 = horiz * aim
answer2 = horiz * depth

advent.print_answer(1, answer1)
advent.print_answer(2, answer2)

0 comments on commit d7a3fa6

Please sign in to comment.