Expand description
Β§Amphipod
Our high level approach is an A* search over all possible burrow states. Three techniques are used to speed things up.
Firstly a good choice of heuristic is crucial. The heuristic used has the following characteristics:
- Exactly correct for optimal moves.
- Cheap to update on each subsequent move.
Secondly pruning states to reduce the search space is very beneficial. Two approaches are used:
- A cache of previously seen states. If amphipods are in the same position but with a higher cost then the current state will never be optimal and can be pruned.
- Detecting deadlocked states where an amphipod in the hallway prevents any possible solution. Exploring any further is a waste of time.
Thirdly low level bit manipulation is used to represent the burrow state size compactly in only 16 bytes for faster copying and hashing.
StructsΒ§
- Burrow π
- Combine hallway and four rooms into a complete burrow representation in only 8 + 4 * 2 = 16 bytes.
- Hallway π
- Pack the state of the hallway into a
usize
. Each hallway position is represented by a nibble with the pod type (plus additionally empty or room entrance markers) for a total of 44 bits. - Room π
- Pack the room state into only 2 bytes.
ConstantsΒ§
- A π
- The values of
A
,B
,C
andD
are used heavily to calculate room indices. - B π
- C π
- COST π
- D π
- EMPTY π
- ROOM π
FunctionsΒ§
- best_
possible π - Heuristic of the lowest possible energy to organize the burrow. Assumes that amphipods can move through the hallway unblocked.
- condense π
- Starting from a burrow of a specific kind, searches the hallway and other rooms from either left or right direction, returning all amphipods of that kind to the burrow. Stops searching immediately if blocked.
- deadlock_
left π - Checks for a situation where an
A
amphipod can block other amphipods in the leftmost burrow. - deadlock_
right π - Mirror image situation to
deadlock_left
where aD
amphipod could block others. - deadlock_
room π - Detects situation where amphipods in the hallway need to move past each other but mutually block any further progress.
- expand π
- Searches the hallway in either the right or left direction, pushing a new state to the priority queue if itβs possible to place an amphipod there.
- organize π
- A* search over all possible burrow states until we find the lowest cost to organize.
- parse
- Subtracts the ASCII value of
A
from each character of the input so that amphipod values match the constants defined above. - part1
- Part one is a special case of the full burrow where two amphipods of each type are already in the correct position in each room.
- part2
- Part two adds the middle amphipods as specified in the problem statement.