aboutsummaryrefslogtreecommitdiff
path: root/2024/puzzle-2.py
diff options
context:
space:
mode:
authorAryadev Chavali <aryadev@aryadevchavali.com>2024-12-03 16:40:08 +0000
committerAryadev Chavali <aryadev@aryadevchavali.com>2024-12-03 16:40:08 +0000
commite253bc500686b7d9adec1686d20c75714cf2ddf0 (patch)
tree5bfc137901f2c86e582ad2bc05882e6fba0c0ad6 /2024/puzzle-2.py
parent88351633d250638b02ad499123ec44bb39edf3ef (diff)
downloadadvent-of-code-e253bc500686b7d9adec1686d20c75714cf2ddf0.tar.gz
advent-of-code-e253bc500686b7d9adec1686d20c75714cf2ddf0.tar.bz2
advent-of-code-e253bc500686b7d9adec1686d20c75714cf2ddf0.zip
Solve round 2 and 3 for 2024
Diffstat (limited to '2024/puzzle-2.py')
-rw-r--r--2024/puzzle-2.py43
1 files changed, 43 insertions, 0 deletions
diff --git a/2024/puzzle-2.py b/2024/puzzle-2.py
new file mode 100644
index 0000000..98f2efd
--- /dev/null
+++ b/2024/puzzle-2.py
@@ -0,0 +1,43 @@
+lines = []
+with open("2-input", "r") as fp:
+ lines = fp.readlines()
+
+levels = [list(map(int, line.strip().split(" "))) for line in lines]
+
+def is_good_level_1(level):
+ # 1) Is decreasing
+ # 2) Sliding window of two cells (x, y) => 1 <= |x-y| <= 3
+ # figure out if decreasing from first two
+ decreasing = level[0] > level[1]
+ for i in range(len(level) - 1):
+ x = level[i]
+ y = level[i + 1]
+ diff = abs(x - y)
+ if (decreasing and x < y) or (not decreasing and x > y) or not (diff <= 3 and diff >= 1):
+ return False
+ return True
+
+good_levels = [level for level in levels if is_good_level_1(level)]
+print(f"Round 1: {len(good_levels)}")
+
+def check_two_levels(x, y, decreasing):
+ diff = abs(x - y)
+ return not ((decreasing and x < y) or (not decreasing and x > y) or not (diff <= 3 and diff >= 1))
+
+def is_good_level_2(level):
+ # 1) Is decreasing
+ # 2) Sliding window of two cells (x, y) => 1 <= |x-y| <= 3
+ # 3) Can remove any one item to make it safe
+ ret = is_good_level_1(level)
+ if not ret:
+ # Consider slices of the level and check if they're good
+ slices = [level[:i] + level[i + 1:] for i in range(len(level))]
+ for s in slices:
+ if is_good_level_1(s):
+ return True
+ else:
+ return True
+ return False
+
+good_levels = [level for level in levels if is_good_level_2(level)]
+print(f"Round 2: {len(good_levels)}")