2018-12-03 - No Matter How You Slice It
(original .ipynb)
import re
data = open("puzzle_input/day3.txt").readlines()
class Claim(object):
def __init__(self, raw_input):
parsed_input = re.search("^#(\d+) @ (\d+),(\d+): (\d+)x(\d+)$", raw_input)
assert(len(parsed_input.groups()) == 5)
claim_id = int(parsed_input.group(1))
left_pad = int(parsed_input.group(2))
top_pad = int(parsed_input.group(3))
width = int(parsed_input.group(4))
height = int(parsed_input.group(5))
self.claim_id = claim_id
self.left = left_pad
self.top = top_pad
self.width = width
self.height = height
self.overlaps = 0
def has_overlap(self, other):
return not(self.left > other.left + other.width
or self.left + self.width < other.left
or self.top > other.top + other.height
or self.top + self.height < other.top)
def create_grid(width, height):
grid = []
for i in range(height + 1):
grid.append([ 0 ] * width)
return grid
claims = [ Claim(d) for d in data ]
# Part 1
# Counting how many square inches are covered by >1 claim. I basically just create a NxM grid
# of integers, loop through all claims point-by-point incrementing the value at each grid point
max_grid_x = max( [ claim.left + claim.width for claim in claims ] )
max_grid_y = max( [ claim.top + claim.height for claim in claims ] )
grid = create_grid(max_grid_x, max_grid_y)
for claim in claims:
for x in range(claim.left, claim.left + claim.width):
for y in range(claim.top, claim.top + claim.height):
grid[x][y] += 1
overlaps = 0
for row in grid:
for col in row:
if col > 1:
overlaps += 1
print("part one:", overlaps)
part one: 117505
# Part 2
# Luckily I mis-read the first question and implemented that nasty "has_overlap" function
# so just loop over the claims and stop when we find one
for i, claim in enumerate(claims):
for other in claims[1 + i:]:
if claim.has_overlap(other):
claim.overlaps += 1
other.overlaps += 1
isolated_claims = [ claim.claim_id for claim in claims if claim.overlaps == 0 ]
assert(len(isolated_claims) == 1)
print("part two:", isolated_claims[0])
part two: 1254