Twelve Days · day 2 · both parts
Day 2: Gift Shop
Both parts can be done by checking every number in the ranges, and that is how I’d start. The interesting part is that the invalid numbers can be written down directly, and then the width of a range stops mattering.
The puzzle, in my words
The input is one line of ranges of product IDs, like 11-22,95-115, both
ends included. An ID is invalid if its digits are some block written out
twice: 55, 6464, 123123. Add up the invalid IDs in all the ranges.
The example has eleven ranges. Eight invalid IDs turn up in them: 11 and 22
in 11-22, 99 in 95-115, 1010 in 998-1012, and 1188511885, 222222,
446446 and 38593859 in four of the others. They add up to 1227775554.
Part 1: a block written twice
Step 1: check every ID
Turn each number into a string and compare its two halves. An odd number of digits can’t be two equal halves, so those are out straight away.
def ranges(text: str) -> list[tuple[int, int]]:
return [tuple(map(int, r.split("-"))) for r in text.strip().split(",") if r.strip()]
def part1(text: str) -> int:
total = 0
for first, last in ranges(text):
for n in range(first, last + 1):
s = str(n)
half = len(s) // 2
if len(s) % 2 == 0 and s[:half] == s[half:]:
total += n
return total
This does one string conversion per ID. Write-ups of the puzzle report real inputs of a few dozen ranges (38 in one of them) holding about two million IDs, with numbers of up to ten digits. On a generated input of that shape (38 ranges, 2,180,000 IDs) it takes about 320 ms. Fine, but it grows with the width of the ranges, and almost every ID it looks at is valid.
Step 2: build the invalid IDs instead
Writing a two-digit block twice is the same as multiplying it by 101:
6464 = 64 × 101. In general, a k-digit block h written twice is
h * (10**k + 1). So the invalid IDs with 2k digits are exactly the
multiples of m = 10**k + 1 whose other factor has k digits.
Inside a range first..last, those factors are every whole number from
first / m rounded up to last / m rounded down, kept within
10**(k-1)..10**k - 1 so the block really has k digits (no leading zero, and
not one digit too many). That’s a run of consecutive numbers, so their sum is
an arithmetic series and there is nothing to loop over:
def repeat_sum(first: int, last: int, k: int, times: int) -> int:
"""Sum of the IDs in [first, last] that are a k-digit block written `times` times."""
m = (10 ** (k * times) - 1) // (10**k - 1) # 101, 1001, 10101, ...
lo = max(10 ** (k - 1), -(-first // m)) # ceiling division
hi = min(10**k - 1, last // m)
return m * (lo + hi) * (hi - lo + 1) // 2 if lo <= hi else 0
def part1(text: str) -> int:
total = 0
for first, last in ranges(text):
for k in range(1, len(str(last)) // 2 + 1):
total += repeat_sum(first, last, k, 2)
return total
The helper already takes the number of copies, which part 2 will need: a
block written three times is h * (10**(2*k) + 10**k + 1), and
(10**(k*times) - 1) // (10**k - 1) is that number of ones spaced k digits
apart (1001001 for k = 3). -(-first // m) is ceiling division: Python’s
// rounds towards minus infinity, so negating before and after rounds up.
Check it on 1188511880-1188511890: ten digits, so k = 5 and m = 100001.
11884 × 100001 = 1188411884 is below the range and 11885 × 100001 =
1188511885 is inside it, so lo is 11885; last // m is 11885 too. The
run is the single block 11885, and the range adds 1188511885.
On the same generated input this takes about 0.05 ms instead of 320.
Part 2: a block written two or more times
Now three copies count too, or five, or seven: 111, 999, 565656, 824824824 and 2121212121 join the list. The example’s sum becomes 4174379265 (worked out by running step 1 below on it; the write-ups I read state the rule but not this total). One thing to watch: 222222 is 2 written six times, 22 three times and 222 twice, and it still counts once.
Step 1: try every block length
The scan again, now with every block length that divides the number of
digits. break after the first one that fits, so that 222222 is added once:
def part2(text: str) -> int:
total = 0
for first, last in ranges(text):
for n in range(first, last + 1):
s = str(n)
for k in range(1, len(s) // 2 + 1):
if len(s) % k == 0 and s[:k] * (len(s) // k) == s:
total += n
break
return total
About 1.1 s on the generated input.
Step 2: the doubled-string trick
There’s an old trick for this. A string is a block written two or more times exactly when it appears inside itself doubled, with the first and last characters dropped:
def part2(text: str) -> int:
return sum(
n
for first, last in ranges(text)
for n in range(first, last + 1)
if (s := str(n)) in (s + s)[1:-1]
)
"6464" doubled is "64646464", trimmed "464646", and "6464" is in it.
"6465" gives "465646", and it isn’t. Why it works: if s is a block
written several times, the copy that starts one block into s + s is s
itself, and the trimming doesn’t touch it. The other way round, finding s
at a shift i inside s + s means s is unchanged by rotating it i
places, which makes it a block of gcd(i, len(s)) digits repeated. The
trimming only rules out the two trivial matches at shift 0 and shift
len(s).
It’s the same scan, so it still looks at every ID, but the Python loop over
block lengths becomes a single in, and it runs in about half the time:
540 ms.
Step 3: build them, and keep a set
Back to building. An ID of length digits can be a k-digit block written
length // k times for every k that divides length, and the multiplier
from part 1 handles any number of copies. A range like 95-115 covers two
lengths, so both are tried. The same ID can come out of several splits, so
the IDs of a range go into a set first:
def part2(text: str) -> int:
total = 0
for first, last in ranges(text):
found = set()
for length in range(len(str(first)), len(str(last)) + 1):
for k in range(1, length // 2 + 1):
if length % k:
continue
m = (10**length - 1) // (10**k - 1)
lo = max(10 ** (k - 1), -(-first // m))
hi = min(10**k - 1, last // m)
found.update(m * h for h in range(lo, hi + 1))
total += sum(found)
return total
The set is per range, not one for the whole input. A single set looks the same, and the tests caught the difference: when two ranges overlap, the scan counts a shared ID twice and a single set counts it once. Real inputs aren’t reported to have overlapping ranges, but the build should agree with the scan whatever the input.
0.07 ms on the generated input. It still makes every invalid ID, so its time grows with how many there are, but there are few: on a generated input of 38 ranges holding 10^10 IDs it takes 4.5 ms. Extrapolating from the timings above, the scans would need somewhere between half an hour and an hour and a half there (not run).
Step 4: inclusion-exclusion, no set at all
The set is only there to stop double counting, and that can be done with arithmetic. Splits nest: 2 written six times is also 222 written twice and 22 written three times, because 2 and 3 divide 6. But 121212 (12 three times) is not a three-digit block twice. So the invalid IDs of a given length are the union of the splits into p copies, one for each prime p that divides the length, and inclusion-exclusion adds up a union of sets without counting anything twice: for six digits, the two-copy sum plus the three-copy sum, minus the six-copy sum (the IDs in both are the ones made of one repeated digit).
The signs follow the Möbius function μ(d) of the number of copies: −μ(d) is +1 for one prime factor, −1 for two different ones, +1 for three, and 0 when a prime appears twice (four copies are already inside two copies, so they’re skipped):
def mobius(d: int) -> int:
"""mu(d): 0 if a square divides d, else (-1) ** (number of prime factors)."""
sign, p = 1, 2
while p * p <= d:
if d % p == 0:
d //= p
if d % p == 0:
return 0
sign = -sign
p += 1
return -sign if d > 1 else sign
def part2(text: str) -> int:
total = 0
for first, last in ranges(text):
for length in range(len(str(first)), len(str(last)) + 1):
for copies in range(2, length + 1):
if length % copies == 0 and (mu := mobius(copies)):
total -= mu * repeat_sum(first, last, length // copies, copies)
return total
Check it on 222220-222224: two copies finds 222222, three copies finds
222222, six copies finds 222222 and is subtracted. 1 + 1 − 1 = 1.
For these inputs it makes no practical difference: 0.05 ms against the set’s 0.07 ms, and 0.08 ms against 4.5 ms on the 10^10-ID input. What it buys is that the work no longer depends on how many invalid IDs there are, only on the number of ranges and digits. The tests check it against step 3 on ranges of 12, 18, 30 and 60 digits, where a scan is out of the question, and the builds against the scans on a few hundred random sets of ranges.
All of this was checked on the puzzle’s example and on generated inputs, not on a puzzle input of my own.