Twelve Days · day 6 · both parts
Day 6: Trash Compactor
Part 1 is a transpose. Part 2 reads the same worksheet sideways, and the interesting part is that the whitespace you were happy to throw away in part 1 is now the data.
The puzzle, in my words
A worksheet holds arithmetic problems side by side. Each problem is a few
numbers stacked on top of each other with + or * underneath, and a
column of spaces separates one problem from the next. Work out every problem
and add up the results.
The example has four problems:
123 328 51 64
45 64 387 23
6 98 215 314
* + * +
That’s 123 × 45 × 6 = 33210, 328 + 64 + 98 = 490, 51 × 387 × 215 = 4243455 and 64 + 23 + 314 = 401: 4277556 in total. Note the trailing spaces on three of those lines. They don’t matter yet.
Part 1: one number per line
Step 1: the first version
Split each line on whitespace. Every line then has one entry per problem, so
problem i is entry i of every line, and its operator is entry i of the
last line.
def lines(text: str) -> list[str]:
return [line for line in text.splitlines() if line.strip()]
def part1(text: str) -> int:
rows = [line.split() for line in lines(text)]
numbers, ops = rows[:-1], rows[-1]
total = 0
for i in range(len(ops)):
if ops[i] == "+":
result = 0
for row in numbers:
result += int(row[i])
else:
result = 1
for row in numbers:
result *= int(row[i])
total += result
return total
str.split() with no argument splits on runs of whitespace and drops
leading and trailing whitespace, which is exactly what makes " 45 64 387 23 "
come out as four clean entries.
Step 2: transpose with zip(*rows)
Indexing entry i of every row is a transpose done by hand. zip(*rows)
does it directly: it yields one tuple per column, here one whole problem
with its operator last. math.prod (Python 3.8+) is to * what sum is to
+, so a dict from symbol to function replaces the if:
import math
OPS = {"+": sum, "*": math.prod}
def part1(text: str) -> int:
*numbers, ops = (line.split() for line in lines(text))
return sum(OPS[op](map(int, col)) for *col, op in zip(*numbers, ops))
*col, op unpacks each column tuple into everything-but-the-last and the
last. This version isn’t faster: on a generated worksheet of 1,000 problems
both take well under a millisecond, the loops slightly less. It’s shorter,
and the shape of the code is the shape of the puzzle.
Part 2: one number per column
Now the worksheet is read the cephalopod way: right to left, one number per character column, its digits top to bottom. Blank columns still separate the problems and the operator is still at the bottom. The rightmost problem,
64
23
314
+
has columns (from the right) 4, 431 and 623, so it is
4 + 431 + 623 = 1058. The others become 175 × 581 × 32 = 3253600,
8 + 248 + 369 = 625 and 356 × 24 × 1 = 8544, for a total of 3263827.
line.split() can’t help any more: it throws away where each digit sits,
which is now the whole point.
Step 1: walk the columns
Do what the rule says. Pad the lines to the same width (in case an editor stripped the trailing spaces), then walk the character columns from right to left. A column’s digits, top to bottom, are a number; a column of nothing but spaces, or running off the left edge, closes the problem.
def part2(text: str) -> int:
rows = lines(text)
width = max(len(line) for line in rows)
rows = [line.ljust(width) for line in rows]
numbers, ops = rows[:-1], rows[-1]
total = 0
current: list[int] = []
op = None
for x in range(width - 1, -2, -1):
if x == -1 or all(line[x] == " " for line in rows):
if current:
if op == "+":
total += sum(current)
else:
total += math.prod(current)
current, op = [], None
continue
digits = "".join(row[x] for row in numbers if row[x] != " ")
if digits:
current.append(int(digits))
if ops[x] != " ":
op = ops[x]
return total
The range runs down to -1 so that the leftmost problem gets closed by the
same code as the others.
Step 2: transpose the characters
Part 1 transposed the split lines; part 2 can transpose the characters
themselves. zip(*rows) would do it if every line had the same length, but
zip stops at the shortest argument, so one stripped trailing space would
silently cut off the last column. itertools.zip_longest pads instead.
Each column is then a string like "1 *" or "24 ". itertools.groupby
with key=str.isspace splits the sequence of columns into runs of blank
and non-blank ones, and each non-blank run is one problem. Since + and
* don’t care about order, there is no need to go right to left:
from itertools import groupby, zip_longest
def part2(text: str) -> int:
cols = ["".join(col) for col in zip_longest(*lines(text), fillvalue=" ")]
total = 0
for blank, run in groupby(cols, key=str.isspace):
if not blank:
run = list(run)
op = next(c[-1] for c in run if c[-1] != " ")
total += OPS[op](int(c[:-1].replace(" ", "")) for c in run)
return total
c[:-1] drops the operator line’s character, and replace(" ", "")
removes the blanks. In the example a column’s spaces are only above or below
its digits, and int() would accept those on its own, since it ignores
leading and trailing whitespace. But a shorter number between two longer
ones leaves a gap in the middle of a column: with 328, 6 and 98 all
aligned left, the second column is 2, space, 8, and int("2 8") raises
a ValueError. I don’t know whether real inputs ever have such a column;
reading the digits with the blanks skipped (28) covers it either way, and a
test checks that sheet.
On the same generated worksheet (1,000 problems, five lines of about 4,500 characters) the column walk takes about 2 ms and this version about 1 ms. The tests run both against each other, and against a third, separate restatement of the rule, on 300 random worksheets with numbers aligned left or right at random.
All of this was checked on the puzzle’s examples and on generated worksheets, not on a puzzle input of my own.