day3 wont work with multiple specials
axsk opened this issue · 1 comments
axsk commented
i really like your solution
however, i believe if a number has multiple adjacent specials, you would count the number multiple times.
how would you work around this?
(c.f.
Line 33 in 336061f
ephemient commented
That doesn't occur in the inputs but would be easy to handle, just a bit more verbose.
--- a/py/aoc2023/day3.py
+++ b/py/aoc2023/day3.py
@@ -29,9 +29,11 @@ def _parse(data):
for match in NUMBER_RE.finditer(line):
number = int(match.group(0))
x0, x1 = match.span()
- for yy in range(max(y - 1, 0), min(y + 2, len(lines))):
- for match in SYMBOL_RE.finditer(lines[yy], x0 - 1, x1 + 1):
- yield match.start(), yy, number
+ yield [
+ (match.start(), yy)
+ for yy in range(max(y - 1, 0), min(y + 2, len(lines)))
+ for match in SYMBOL_RE.finditer(lines[yy], x0 - 1, x1 + 1)
+ ], number
def part1(data):
@@ -39,7 +41,7 @@ def part1(data):
>>> part1(SAMPLE_INPUT)
4361
"""
- return sum(number for _, _, number in _parse(data))
+ return sum(number for symbols, number in _parse(data) if symbols)
def part2(data):
@@ -48,8 +50,9 @@ def part2(data):
467835
"""
gears = defaultdict(list)
- for x, y, number in _parse(data):
- gears[x, y].append(number)
+ for symbols, number in _parse(data):
+ for symbol in symbols:
+ gears[symbol].append(number)
return sum(prod(numbers) for numbers in gears.values() if len(numbers) == 2)