Skip to content

Instantly share code, notes, and snippets.

@mlesniew
Created December 22, 2021 22:00
Show Gist options
  • Save mlesniew/e52830ba2a3c65d2700fcfa0509f27d8 to your computer and use it in GitHub Desktop.
Save mlesniew/e52830ba2a3c65d2700fcfa0509f27d8 to your computer and use it in GitHub Desktop.
import re
import sys
# 3d regions represented as tuples of 3 tuples: ((x1, x2), (y1, y2), (z1, z2))
def valid(r):
return all(c[0] <= c[1] for c in r)
def count_cubes(r):
ret = 1
for c in r:
ret *= c[1] - c[0] + 1
return ret
def count_cubes_init(r):
INIT_REGION = tuple((-50, 50) for _ in range(3))
if overlap(INIT_REGION, r):
return count_cubes(common(INIT_REGION, r))
else:
return 0
def overlap(r1, r2):
return all(c1[0] <= c2[1] and c1[1] >= c2[0] for c1, c2 in zip(r1, r2))
def common(r1, r2):
return tuple((max(c1[0], c2[0]), min(c1[1], c2[1])) for c1, c2 in zip(r1, r2))
def differ(r1, r2):
if not overlap(r1, r2):
return [r1]
common_ = common(r1, r2)
regions = [
((common_[0][1] + 1, r1[0][1]), r1[1], common_[2]),
((r1[0][0], common_[0][0] - 1), r1[1], common_[2]),
(common_[0], (common_[1][1] + 1, r1[1][1]), common_[2]),
(common_[0], (r1[1][0], common_[1][0] - 1), common_[2]),
(r1[0], r1[1], (common_[2][1] + 1, r1[2][1])),
(r1[0], r1[1], (r1[2][0], common_[2][0] - 1)),
]
return [r for r in regions if valid(r)]
STEPS = re.findall(
r"(on|off) x=(-?[0-9]+)\.\.(-?[0-9]+),y=(-?[0-9]+)\.\.(-?[0-9]+),z=(-?[0-9]+)\.\.(-?[0-9]+)",
sys.stdin.read(),
)
regions = []
for onoff, *coords in STEPS:
x1, x2, y1, y2, z1, z2 = [int(c) for c in coords]
region = ((x1, x2), (y1, y2), (z1, z2))
# subtract from all existing regions
regions = sum((differ(r, region) for r in regions), start=[])
# if it's an "on" region, add it
if onoff == "on":
regions.append(region)
print("Step 1:", sum(count_cubes_init(r) for r in regions))
print("Step 2:", sum(count_cubes(r) for r in regions))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment