Skip to content
advent of code 2015

day 13

knights of the dinner table

approach

a regex turns each line into an entry of a defaultdict keyed by (person, neighbour), negative for losses. the cost of a seating is the sum, for every seat, of what that person feels about both neighbours, with indices wrapping around the table.

part 1 takes the maximum over every permutation of the guests. part 2 adds "Me" to the set; since the dict defaults to zero, no extra entries are needed. a comment notes that fixing one seat would remove the circular symmetry and speed it up, but it is left as full brute force.

the trick

a defaultdict(int) makes the extra guest free: every missing pair is already zero.

python
def cost(p, d):
    n = len(p)
    return sum(d[(p[i], p[(i+1) % n])] + d[(p[i], p[i-1])] for i in range(n))