| i | i+3 | s_i | s_(i+3) | Equal? |
|---|---|---|---|---|
| 0 | 3 | r | r | Yes |
| 1 | 4 | g | g | Yes |
| 2 | 5 | b | b | Yes |
| 3 | 6 | r | r | Yes |
| 4 | 7 | g | g | Yes |
| 5 | 8 | b | b | Yes |
I found day 4 particularly tricky this year. Eventually, I broke down and asked Claude to give me a hint. As penance, I am writing up my solution as a blog post to explain to someone (if not only myself) how one perhaps could have arrived at a solution independently.
The printer takes a finite set of \(p\) instructions
\[ t_0, t_1, \cdots, t_{p-1} \]
and repeats them indefinitely to create an infinite sequence
\[s = t_0, t_1, \cdots, t_{p-1}, t_0, t_1, \cdots, t_{p-1}, t_0, t_1, \cdots, t_{p-1} \>. \]
The sequence \(s\) is therefore \(p\)-periodic. However, that does not mean \(p\) is the smallest period. Consider the sequence rgbrgbrgb. Although \(p=9\) here, and any \(s\) created from it would also have period 9, there is a smaller period (namely, 3). It is harder to formalize why this sequence should have period 3 than it is to see it by inspection. To do so, we can just check a bunch of \(p\) and determine if the sequence displays period \(p\).
Let’s check \(p=1\). If the sequence
rgbrgbrgbhad period \(p=1\) then this would mean that \(t_i = t_{i+1}\). Clearly, this is not the case – the first instruction in the sequence isrand the second isg.Let’s check \(p=2\). If the sequence
rgbrgbrgbhad period \(p=2\) then this would mean that \(t_i = t_{i+2}\). Clearly, this is not the case – the first instruction in the sequence isrand the third isb.Let’s check \(p=3\). If the sequence
rgbrgbrgbhad period \(p=3\) then this would mean that \(t_i = t_{i+3}\). Clearly, this is the case – the first instruction in the sequence isrand the fourth isr. The second instruction isgand the fifth instruction is alsog. The third instruction isband the sixth instruction is alsob.
Generally, the sequence will be \(p\)-periodic if
\[ s_{i} = s_{i+p} \quad \forall i \>, \] or, in terms of the finite set of instructions
\[ s_{i} = t_{(i \bmod p)} \>. \]
Yet another way to phrase this is in terms of remainders modulo \(p\). If the sequence is \(p\)-periodic, then \(i\) and \(i+p\) will both have the same remainder modulo \(p\) (since \(p \bmod p=0\)). Therefore, we can collect instructions in the sequence for which the indices share a remainder and determine if they are all the same. If they are, then the sequence is \(p\)-periodic. Below, I do this in code.
p = 1
| remainder | s | all_same |
|---|---|---|
| 0 | ['r', 'g', 'b', 'r', 'g', 'b', 'r', 'g', 'b'] | False |
p = 2
| remainder | s | all_same |
|---|---|---|
| 0 | ['r', 'b', 'g', 'r', 'b'] | False |
| 1 | ['g', 'r', 'b', 'g'] | False |
p = 3
| remainder | s | all_same |
|---|---|---|
| 0 | ['r', 'r', 'r'] | True |
| 1 | ['g', 'g', 'g'] | True |
| 2 | ['b', 'b', 'b'] | True |
The day 4 problem does not ask us to determine if a sequence is \(p\)-periodic, but understanding how to do this will be important. Let’s jump to another example from the question, the sequence o??v???y. Remember that the ? are essentially a degree of freedom – we can choose them to be anything we want. The question claims that a sequence of period 5 could generate this sequence, so let’s print out similar tables to the above in order to verify this, ranging from period 1 to 5. They are shown below.
p = 1
| remainder | s | all_same |
|---|---|---|
| 0 | ['o', '?', '?', 'v', '?', '?', '?', 'y'] | False |
p = 2
| remainder | s | all_same |
|---|---|---|
| 0 | ['o', '?', '?', '?'] | False |
| 1 | ['?', 'v', '?', 'y'] | False |
p = 3
| remainder | s | all_same |
|---|---|---|
| 0 | ['o', 'v', '?'] | False |
| 1 | ['?', '?', 'y'] | False |
| 2 | ['?', '?'] | True |
p = 4
| remainder | s | all_same |
|---|---|---|
| 0 | ['o', '?'] | False |
| 1 | ['?', '?'] | True |
| 2 | ['?', '?'] | True |
| 3 | ['v', 'y'] | False |
p = 5
| remainder | s | all_same |
|---|---|---|
| 0 | ['o', '?'] | False |
| 1 | ['?', '?'] | True |
| 2 | ['?', 'y'] | False |
| 3 | ['v'] | True |
| 4 | ['?'] | True |
Aha! Now we see something interesting. The important constraint becomes apparent now; if all instructions with the same remainder must be the same, then the smallest period is that which produces identical remainders for known instructions!
To see what I mean, consider the tables for 4 and 5. If the period were 4, then the instructions v and y would have the same remainder, which would violate the requirement I have stated above. However, table 5 puts all known instructions in their own remainder possibly with the unknown instructions. Since the unknown instructions are degrees of freedom, we can simply choose those instructions so that instructions with the same remainder are homogeneous.
The puzzle calls each sequence a barcode, so I will use that term from here on. Here is some pseudocode for the solution:
sum = 0
for barcode in barcodes:
n = length(barcode)
for p in 1:n:
compute index remainders modulo p
g = TRUE if all known instructions within a group are homogeneous
if g:
break
sum += p
Here is the solution translated into Python:
examples = {
"rgbrgbrgbr": 3,
"?rv": 2,
"o??v???y": 5,
"??bg?v??": 4,
"??b?????": 1,
"???": 1,
}
total = 0
for barcode, expected in examples.items():
n = len(barcode)
for p in range(1, n + 1):
# group the known instructions by remainder modulo p
groups = {}
for i in range(n):
if barcode[i] != '?':
r = i % p
if r not in groups:
groups[r] = []
groups[r].append(barcode[i])
# a group is homogeneous if every instruction equals the first
g = True
for colors in groups.values():
for c in colors:
if c != colors[0]:
g = False
if g:
break
status = "OK" if p == expected else "FAIL"
print(f"{barcode:12} expected={expected} got={p} {status}")
total += p
print("total:", total)rgbrgbrgbr expected=3 got=3 OK
?rv expected=2 got=2 OK
o??v???y expected=5 got=5 OK
??bg?v?? expected=4 got=4 OK
??b????? expected=1 got=1 OK
??? expected=1 got=1 OK
total: 16
That works, but can we do better?
A Shorter Solution
Re-examining that script shows two important parts:
- Looping over the possible periods, and then
- Looping over the instructions in the barcode.
In those loops, we compute the remainder for each known instruction modulo \(p\) and then group those instructions with the same remainder. There is an easier way to do this using slicing in Python.
Consider again the barcode rgbrgbrgb. To obtain all instructions with the same remainder modulo \(p\), I just need to do a slice like the following
s = 'rgbrgbrgb'
p = 3
for b in range(p):
print(s[b::p])rrr
ggg
bbb
Note that for \(p=3\), all instructions with the same remainder are homogeneous (as is expected). How do we tersely check if this is the case in Python? Use len and set!
s = 'rgbrgbrgb'
p = 3
for b in range(p):
# True if all instructions in s[b::p] are the same, else False
check = len(set(s[b::p])) <=1
print(check)True
True
True
All that is left to do is to loop over the periods and return the smallest period
s = 'rgbrgbrgb'
for p in range(1, len(s) + 1):
check = True
for b in range(p):
# False if any group has more than one distinct instruction
if len(set(s[b::p])) > 1:
check = False
if check:
break
print(p)3
Again, this is not what the question asks for, but is useful nonetheless. To account for the ?, we can just remove those from the set since we can choose them to be whatever we need them to be.
examples = {
"rgbrgbrgbr": 3,
"?rv": 2,
"o??v???y": 5,
"??bg?v??": 4,
"??b?????": 1,
"???": 1,
}
total = 0
for s in examples:
expected = examples[s]
for p in range(1, len(s) + 1):
check = True
for b in range(p):
# False if any group has more than one distinct instruction
# Note the removal of the ?
if len(set(s[b::p]) - set('?')) > 1:
check = False
if check:
break
status = "OK" if p == expected else "FAIL"
print(f"{s:12} expected={expected} got={p} {status}")
total += p
print(total)rgbrgbrgbr expected=3 got=3 OK
?rv expected=2 got=2 OK
o??v???y expected=5 got=5 OK
??bg?v?? expected=4 got=4 OK
??b????? expected=1 got=1 OK
??? expected=1 got=1 OK
16
An Even Terser Solution
I like code golf, and Python allows for some very terse solutions to Advent of Code using generators. Here is as terse as it can be made (according to Claude):
examples = {
"rgbrgbrgbr": 3,
"?rv": 2,
"o??v???y": 5,
"??bg?v??": 4,
"??b?????": 1,
"???": 1,
}
sum(
next(p for p in range(1, len(b) + 1)
if all(len(set(b[r::p]) - {'?'}) <= 1 for r in range(p)))
for b in examples
)16