Part 1

The device on your wrist beeps several times, and once again you feel like you're falling.

"Situation critical," the device announces. "Destination indeterminate. Chronal interference detected. Please specify new target coordinates."

The device then produces a list of coordinates (your puzzle input). Are they places it thinks are safe or dangerous? It recommends you check manual page 729. The Elves did not give you a manual.

If they're dangerous, maybe you can minimize the danger by finding the coordinate that gives the largest distance from the other points.

Using only the Manhattan distance, determine the area around each coordinate by counting the number of integer X,Y locations that are closest to that coordinate (and aren't tied in distance to any other coordinate).

Your goal is to find the size of the largest area that isn't infinite. For example, consider the following list of coordinates:

1, 1
1, 6
8, 3
3, 4
5, 5
8, 9

If we name these coordinates A through F, we can draw them on a grid, putting 0,0 at the top left:

..........
.A........
..........
........C.
...D......
.....E....
.B........
..........
..........
........F.

This view is partial - the actual grid extends infinitely in all directions. Using the Manhattan distance, each location's closest coordinate can be determined, shown here in lowercase:

aaaaa.cccc
aAaaa.cccc
aaaddecccc
aadddeccCc
..dDdeeccc
bb.deEeecc
bBb.eeee..
bbb.eeefff
bbb.eeffff
bbb.ffffFf

Locations shown as . are equally far from two or more coordinates, and so they don't count as being closest to any.

In this example, the areas of coordinates A, B, C, and F are infinite - while not shown here, their areas extend forever outside the visible grid. However, the areas of coordinates D and E are finite: D is closest to 9 locations, and E is closest to 17 (both including the coordinate's location itself). Therefore, in this example, the size of the largest area is 17.

What is the size of the largest area that isn't infinite?


In [1]:
from pathlib import Path
import itertools
from collections import Counter
from collections import defaultdict
from pprint import pprint
import re
from datetime import datetime
import numpy as np
import functools

In [2]:
lines = Path('input').read_text().strip().split('\n')

In [39]:
points = [tuple(map(int,l.replace(' ','').split(','))) for l in lines]

In [4]:
@functools.lru_cache(maxsize= 32)
def offsets_from_distance(dist):
    result = set()
    for x_d in range(-dist, dist+1):
        for y_d in range(-dist, dist+1):
            if abs(x_d) + abs(y_d) == dist:
                result.add((x_d, y_d))
                   
    return np.copy(np.array(list(result)))

In [50]:
SIZE = 353

In [16]:
#TEST
SIZE = 10
points = [(1, 1),
(1, 6),
(8, 3),
(3, 4),
(5, 5),
(8, 9)]

In [ ]:
data = np.chararray((SIZE,SIZE), itemsize=10, order='F', unicode=True)
data[:] = '__'
for i, (row, col) in enumerate(points):
    data[row][col] = str.zfill(str(i), 2)
dist = 1
point_labels = set()
all_fully_expanded = defaultdict(bool)

for dist in range(1, SIZE):
    last_data = np.copy(data)
    cells = offsets_from_distance(dist)
    for i, (row, col) in enumerate(points):
        num = str.zfill(str(i), 2)
        point_labels.add(num)
        if not all_fully_expanded[num]:
            this_cells = np.copy(cells)
            this_cells[:,0] += row
            this_cells[:,1] += col
            this_cells = np.take(this_cells,
                                 np.where(np.logical_and(
                                     np.logical_and(this_cells[:,0] < SIZE, this_cells[:,0] >= 0),
                                     np.logical_and(this_cells[:,1] < SIZE, this_cells[:,1] >= 0)))[0],
                                 axis=0)

            fully_expanded = True
            for (row2, col2) in this_cells:
                if data[row2][col2] == '__':
                    data[row2][col2] = num
                    fully_expanded = False
                elif data[row2][col2] == '..':
                    pass
                elif last_data[row2][col2] == '__':
                    data[row2][col2] += ','+num
                    fully_expanded = False
                else:
                    pass

            all_fully_expanded[num] = fully_expanded

            new_collisions = np.argwhere(np.char.count(data, ',')>0)
            for row2, col2 in new_collisions:
                if last_data[row2][col2] == '__':
                    data[row2][col2] = '..'
                else:
                    data[row2][col2] = last_data[row2][col2]
    if not ('__' in data):
        break

In [10]:
enclosed_points = point_labels - (set(data[0,:]) | set(data[:,0]) |set(data[-1,:]) | set(data[:,-1]))

In [11]:
counts = Counter({label: np.sum(data.count(label)) for label in enclosed_points})

In [12]:
counts.most_common(1)


Out[12]:
[('21', 3722)]

Part 2

On the other hand, if the coordinates are safe, maybe the best you can do is try to find a region near as many coordinates as possible.

For example, suppose you want the sum of the Manhattan distance to all of the coordinates to be less than 32. For each location, add up the distances to all of the given coordinates; if the total of those distances is less than 32, that location is within the desired region. Using the same coordinates as above, the resulting region looks like this:

..........
.A........
..........
...###..C.
..#D###...
..###E#...
.B.###....
..........
..........
........F.

In particular, consider the highlighted location 4,3 located at the top middle of the region. Its calculation is as follows, where abs() is the absolute value function:

Distance to coordinate A: abs(4-1) + abs(3-1) =  5
Distance to coordinate B: abs(4-1) + abs(3-6) =  6
Distance to coordinate C: abs(4-8) + abs(3-3) =  4
Distance to coordinate D: abs(4-3) + abs(3-4) =  2
Distance to coordinate E: abs(4-5) + abs(3-5) =  3
Distance to coordinate F: abs(4-8) + abs(3-9) = 10
Total distance: 5 + 6 + 4 + 2 + 3 + 10 = 30

Because the total distance to all coordinates (30) is less than 32, the location is within the region.

This region, which also includes coordinates D and E, has a total size of 16.

Your actual region will need to be much larger than this example, though, instead including all locations with a total distance of less than 10000.

What is the size of the region containing all locations which have a total distance to all given coordinates of less than 10000?


In [51]:
np_points = np.array(points)

In [53]:
counts_data = np.zeros((SIZE,SIZE), order='F')

In [54]:
from scipy.spatial.distance import cdist

In [55]:
for (row,col) in np.ndindex(counts_data.shape):
    counts_data[row][col] = np.sum(cdist([[row,col]], np_points, metric='cityblock'))

In [56]:
np.count_nonzero(np.where(counts_data < 10000, counts_data, 0))


Out[56]:
44634