From d7a3fa611f39f373167f96556336b3cc1433ad72 Mon Sep 17 00:00:00 2001 From: Marco Bonelli Date: Sat, 4 Dec 2021 13:10:09 +0100 Subject: [PATCH] 2021 d2: merge duplicated variable into one Fixes #11. --- 2021/README.md | 23 ++++++++++++----------- 2021/solutions/day02.py | 16 +++++++--------- 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/2021/README.md b/2021/README.md index b408d7c..0f3811b 100644 --- a/2021/README.md +++ b/2021/README.md @@ -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) @@ -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 diff --git a/2021/solutions/day02.py b/2021/solutions/day02.py index 4423194..6fa78da 100755 --- a/2021/solutions/day02.py +++ b/2021/solutions/day02.py @@ -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)