day4 part2, and some cleanup

This commit is contained in:
Tyrel Souza 2024-12-04 10:19:43 -05:00
parent 2bcab64eff
commit be3fdad22b
4 changed files with 42 additions and 12 deletions

View File

@ -3,11 +3,14 @@ import shared
import itertools
import functools
def is_increasing(sequence):
return all(sequence[i] < sequence[i+1] for i in range(len(sequence) - 1))
return all(sequence[i] < sequence[i + 1] for i in range(len(sequence) - 1))
def is_decreasing(sequence):
return all(sequence[i] > sequence[i+1] for i in range(len(sequence) - 1))
return all(sequence[i] > sequence[i + 1] for i in range(len(sequence) - 1))
def parse_line(row):
for previous, current in zip(row, row[1:]):
@ -15,7 +18,7 @@ def parse_line(row):
if diff >= 1 and diff <= 3:
continue
return 0
if not(is_increasing(row) or is_decreasing(row)):
if not (is_increasing(row) or is_decreasing(row)):
return 0
return 1
@ -34,14 +37,13 @@ def brute_force(row):
if check == 1:
return 1
for x in range(len(row)):
new_row = row[:x] + row[x+1:]
new_row = row[:x] + row[x + 1 :]
check = parse_line(new_row)
if check == 1:
return 1
return 0
# @shared.profile
def part2(rows):
rows = [list(map(int, row.split())) for row in rows]

View File

@ -2,10 +2,11 @@ import shared
import re
from scanf import scanf
# @shared.profile
def part1(rows):
total = 0
r = re.compile(r'mul\(\d+,\d+\)')
r = re.compile(r"mul\(\d+,\d+\)")
for row in rows:
muls = r.findall(row)
for m in muls:
@ -14,11 +15,10 @@ def part1(rows):
print(total)
# @shared.profile
def part2(rows):
total = 0
r = re.compile(r'(mul\(\d+,\d+\)|do\(\)|don\'t\(\))')
r = re.compile(r"(mul\(\d+,\d+\)|do\(\)|don\'t\(\))")
enabled = True
for row in rows:
muls = r.findall(row)

View File

@ -19,9 +19,34 @@ def part1(mx):
# @shared.profile
def part2(rows):
pass
def part2(mx):
count = 0
for idr, row in enumerate(mx):
for idc, c in enumerate(row):
if c != "A":
continue
nb = matrix.get_neighbors_cardinal(mx, idc, idr, diagonals=True)
eastdown= []
for d in ("NW","SE"):
eastdown.append(nb.get(d, {}).get("value"))
if None in eastdown:
continue
eastdown = sorted(eastdown)
westdown = []
for d in ("NE", "SW"):
westdown.append(nb.get(d, {}).get("value"))
if None in westdown:
continue
westdown = sorted(westdown)
if eastdown == ['M','S'] and westdown == ['M', 'S']:
count += 1
print(count)
def main():
mx = matrix.load_matrix_file(shared.get_fname(4), str)
@ -29,9 +54,9 @@ def main():
part1(mx)
print("🕒", elapsed())
rows = [row for row in shared.load_rows(4, True)]
mx = matrix.load_matrix_file(shared.get_fname(4), str)
with shared.elapsed_timer() as elapsed:
part2(rows)
part2(mx)
print("🕒", elapsed())

View File

@ -6,6 +6,7 @@ import functools
import pstats
from itertools import groupby
def all_equal(iterable):
g = groupby(iterable)
return next(g, True) and not next(g, False)
@ -27,9 +28,11 @@ def profile(func):
return inner
def spl(y):
return [int(w) for w in y]
def minmax(l):
return min(l), max(l)