Skip to content

Commit

Permalink
2024 Day 10 Part 2 Complete
Browse files Browse the repository at this point in the history
  • Loading branch information
pcorliss committed Dec 11, 2024
1 parent fd6d8b0 commit c4f90ce
Showing 2 changed files with 40 additions and 13 deletions.
42 changes: 30 additions & 12 deletions 2024/10/daily.py
Original file line number Diff line number Diff line change
@@ -11,41 +11,57 @@ def parse(input_text):
return out

CARDINALS = [(0, 1), (0, -1), (1, 0), (-1, 0)]
CACHE = {}
PEAKS_CACHE = {}
PATH_CACHE = {}

def recurse_path_find(grid, x, y):
if (x, y) in CACHE:
return CACHE[(x, y)]
if (x, y) in PEAKS_CACHE and (x, y) in PATH_CACHE:
return (PEAKS_CACHE[(x, y)], PATH_CACHE[(x, y)])

height = grid[y][x]
if height == 9:
return set([(x, y)])
return (set([(x, y)]), 1)

peaks = set()
paths = 0
for dx, dy in CARDINALS:
new_x = x + dx
new_y = y + dy
if new_x < 0 or new_x >= len(grid[0]) or new_y < 0 or new_y >= len(grid):
continue
if grid[new_y][new_x] != height + 1:
continue
peaks.update(recurse_path_find(grid, new_x, new_y))
new_peaks, paths_count = recurse_path_find(grid, new_x, new_y)
peaks.update(new_peaks)
paths += paths_count

CACHE[(x, y)] = peaks
PEAKS_CACHE[(x, y)] = peaks
PATH_CACHE[(x, y)] = paths
# print(f"{x, y}: {len(peaks)} {list(peaks)}")
return peaks

def path_find(grid):
return (peaks, paths)

def trail_heads(grid):
trail_heads = []
for y in range(len(grid)):
for x in range(len(grid[0])):
if grid[y][x] == 0:
trail_heads.append((x, y))

return trail_heads

def path_find(grid):
peak_score = []
for x, y in trail_heads(grid):
peaks, _ = recurse_path_find(grid, x, y)
peak_score.append(len(peaks))

return peak_score

def path_score(grid):
path_scores = []
for x, y in trail_heads:
path_scores.append(len(recurse_path_find(grid, x, y)))
for x, y in trail_heads(grid):
_, path_score = recurse_path_find(grid, x, y)
path_scores.append(path_score)

return path_scores

@@ -56,7 +72,9 @@ def part1(input_text):
return sum(path_scores)

def part2(input_text):
return 0
grid = parse(input_text)
path_scores = path_score(grid)
return sum(path_scores)

if __name__ == "__main__":
with open(__file__.rsplit('/', 1)[0] + "/input.txt", 'r') as file:
11 changes: 10 additions & 1 deletion 2024/10/daily_test.py
Original file line number Diff line number Diff line change
@@ -25,5 +25,14 @@ def test_path_find(sample_data):
# relies on trail heads being in reading order
assert path_find(grid) == [5, 6, 5, 3, 1, 3, 5, 3, 5]

def test_path_score(sample_data):
grid = parse(sample_data)
assert len(path_score(grid)) == 9
# relies on trail heads being in reading order
assert path_score(grid) == [20, 24, 10, 4, 1, 4, 5, 8, 5]

def test_part1(sample_data):
assert part1(sample_data) == 36
assert part1(sample_data) == 36

def test_part2(sample_data):
assert part2(sample_data) == 81

0 comments on commit c4f90ce

Please sign in to comment.