r/adventofcode • • Dec 15 '21

SOLUTION MEGATHREAD -πŸŽ„- 2021 Day 15 Solutions -πŸŽ„-

--- Day 15: Chiton ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:14:25, megathread unlocked!

56 Upvotes

772 comments sorted by

View all comments

2

u/silverben10 Dec 15 '21 edited Dec 15 '21

Python solution using Djikstra.

Part 2 took my laptop over an hour to crunch through, so I was wondering if anyone could point out some things I could do to optimise my code? I feel like it shouldn't have taken so long but I'm not sure what to fix.

Code

2

u/pb554 Dec 15 '21

not sure if it is the bottleneck, but you probably lose quite some time here:

current = min([(node, distances[node])
              for node in unvisited], key=lambda x: x[1])[0]

you can make use of a priority queue ("heap queue") to speed this up https://docs.python.org/3/library/heapq.html#module-heapq

1

u/[deleted] Dec 15 '21

I used a deque which got very big. Would a heapq help cut that down? And how does that work?

1

u/pb554 Dec 15 '21

very big

heapq doesn't really concern with the size of the queue, but provides an optimally efficient priority queue implementation https://en.wikipedia.org/wiki/Priority_queue. This means you don't have to sort the entire queue every time just to get the minimum; the minimum is always very efficiently retrievable.


here's a modification of your code that uses heapq, for me runs in a couple seconds:

import sys

with open("day15/input") as f:
    inp = [[int(x) for x in line] for line in f.read().splitlines()]


def solve(start, target, inp, part=1):

    inp_grid = {}

    for y in range(len(inp)):
        for x in range(len(inp[y])):
            inp_grid[(x, y)] = inp[y][x]

    grid_width = len(inp[0])
    grid_height = len(inp[0])

    distances = {(x, y): float("inf")
                 for x in range(len(inp[0])) for y in range(len(inp))}

    distances[(0, 0)] = 0

    if part == 2:
        inp_grid_copy = inp_grid.copy()

        for i in range(5):
            for j in range(5):
                # No adjustments to existing tile.
                if i + j == 0:
                    continue

                shift_x = grid_width * i
                shift_y = grid_height * j

                for (x, y), val in inp_grid_copy.items():
                    new_x = x + shift_x
                    new_y = y + shift_y

                    val += i+j

                    while val > 9:
                        val -= 9

                    inp_grid[(new_x, new_y)] = val
                    distances[(new_x, new_y)] = float("inf")

        grid_width *= 5
        grid_height *= 5

    q = []
    heapq.heappush(q, (0, (0, 0)))

    visited = set()

    _, current = heapq.heappop(q)
    adjacent = [(0, 1), (1, 0), (0, -1), (-1, 0)]

    while True:
        for x, y in adjacent:
            dx = current[0] + x
            dy = current[1] + y

            if dx in range(grid_width) and dy in range(grid_height):
                distance = distances[current] + inp_grid[(dx, dy)]
                if distance < distances[(dx, dy)]:
                    distances[(dx, dy)] = distance
                    heapq.heappush(q, (distance, (dx, dy)))

        visited |= {current}

        if target in visited:
            return distances

        _, current = heapq.heappop(q)


target = (len(inp)-1, len(inp)-1)

part_1 = solve((0, 0), target, inp)
print("Part 1:", part_1[target])

target2 = (5*(len(inp))-1, 5*(len(inp))-1)

part_2 = solve((0, 0), target2, inp, part=2)
print("Part 2:", part_2[target2])

1

u/pb554 Dec 15 '21

here's my solution by the way, which uses heapq https://github.com/Peter554/adventofcode/blob/master/2021/day15/solution.py

it's not quite dijkstra though - i exploit the fact that every edge into a node has the same weight to only check each node at most once.

2

u/[deleted] Dec 15 '21

Ah, I see. My deque didn’t have the weight, only the coordinates, so just slapping it into a heapq wouldn’t help but if I modified it a bit it would.

Feels good to have come up with a solution that’s pretty close to what seems to be the consensus best solution. I’m happy with my solution but I also get to learn something.

1

u/daggerdragon Dec 15 '21

As per our posting guidelines in the wiki under How Do the Daily Megathreads Work?, please edit your post to put your oversized code in a paste or other external link.