Last active
December 6, 2018 07:44
-
-
Save synio-wesley/e422d9faa8b548fe5a45d909b48d76bb to your computer and use it in GitHub Desktop.
AOC 2018 - Day 6 - Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Input and shared code between parts | |
coords = [tuple(int(c) for c in line.strip().split(',')) for line in open('day6.txt')] | |
xMax = max(coords, key=lambda c: c[0])[0] | |
yMax = max(coords, key=lambda c: c[1])[1] | |
def manhattanDistance(p, q): | |
return abs(p[0] - q[0]) + abs(p[1] - q[1]); | |
# Part 1 | |
grid = {} | |
closestCount = {} | |
infinites = set() | |
for y in range(-1, yMax + 1): | |
for x in range(-1, xMax + 1): | |
minDistance = -1 | |
closest = None | |
for coord in coords: | |
distance = manhattanDistance(coord, (x, y)) | |
if minDistance == -1 or minDistance > distance: | |
minDistance = distance | |
closest = coord | |
elif minDistance == distance: | |
closest = None | |
grid[(x, y)] = closest | |
if closest not in closestCount: | |
closestCount[closest] = 0 | |
closestCount[closest] += 1 | |
for y in [-1, yMax]: | |
for x in range(-1, xMax + 1): | |
if (x, y) in grid: | |
closest = grid[(x, y)] | |
infinites.add(closest) | |
for x in [-1, xMax]: | |
for y in range(-1, yMax + 1): | |
if (x, y) in grid: | |
closest = grid[(x, y)] | |
infinites.add(closest) | |
closestCount = {coord: closestCount[coord] for coord in closestCount if coord not in infinites} | |
print(max(closestCount.items(), key=lambda c: c[1])[1]) | |
# Part 2 | |
maxDistance = 10000 | |
patchCount = 0 | |
for y in range(-1, yMax + 1): | |
for x in range(-1, xMax + 1): | |
totalDistance = 0 | |
for coord in coords: | |
totalDistance += manhattanDistance(coord, (x, y)) | |
if totalDistance < maxDistance: | |
patchCount += 1 | |
print(patchCount) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment