Advent of Code Day 6

Day 6

Solution to day 6 of Advent of Code https://adventofcode.com/2018/day/6

Data preparation

Since both part 1 and two use the same data, we create a function to read and prepare the data in the file:

In [1]:
def read_file():
    coordinates = []
    with open(r"datafiles\aoc6input.txt",'r') as f:
        for line in f.readlines():
            x,y = line.split(',')
            coordinates.append( (int(x), int(y)))
    return coordinates

Part 1

lets try something simple

In [2]:
import matplotlib.pyplot as plt
%matplotlib inline 


x = [x for x,y in read_file()]
y = [y for x,y in read_file()]

plt.scatter(x, y)
plt.show()

The area isnt very big, so we will attempt a brute force solution

In [3]:
import numpy as np

coordinates = read_file()
area = np.zeros((350,350))

def distance(x,y, x2,y2):
    return abs(x-x2)+abs(y-y2)

def closest(i,j, coordinates):
    distances = [ distance(i,j,*c) for c in coordinates ]
    if distances.count(min(distances)) > 1:
        return -1
    else:
        return distances.index(min(distances))

for i in range(350):
    for j in range(350):
        area[i,j] = closest(i,j, coordinates)

We can plot this using seaborn

In [4]:
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline 

sns.heatmap(area)
Out[4]:
<matplotlib.axes._subplots.AxesSubplot at 0x22ad34adf28>

We will assume that all areas that reach the edge are infinite (maybe not, but lets give it a go). We will color them black.

In [5]:
unique, counts = np.unique(area[0,:], return_counts=True)
area[np.isin(area, unique)] = -1
unique, counts = np.unique(area[:,0], return_counts=True)
area[np.isin(area, unique)] = -1
unique, counts = np.unique(area[-1,:], return_counts=True)
area[np.isin(area, unique)] = -1
unique, counts = np.unique(area[:,-1], return_counts=True)
area[np.isin(area, unique)] = -1
In [6]:
sns.heatmap(area)
Out[6]:
<matplotlib.axes._subplots.AxesSubplot at 0x22ad3744f98>

We can now output the largest , nonblack area:

In [7]:
unique, counts = np.unique(area, return_counts=True)
sorted(counts)[-2]
Out[7]:
3420

Part 2

Brute force again

In [8]:
coordinates = read_file()
area = np.zeros((350,350))

def distance(x,y, x2,y2):
    return abs(x-x2)+abs(y-y2)

def safe(i,j, coordinates):
    return sum([ distance(i,j,*c) for c in coordinates ]) < 10000
    
for i in range(350):
    for j in range(350):
        area[i,j] = safe(i,j, coordinates)

sns.heatmap(area)      
Out[8]:
<matplotlib.axes._subplots.AxesSubplot at 0x22ad3bbec18>
In [9]:
unique, counts = np.unique(area, return_counts=True)
list(zip(unique,counts))
Out[9]:
[(0.0, 75833), (1.0, 46667)]

links

social