The puzzle
Each input line is a barcode. The letters r, o, y, g, b, and v mark readable colors, and ? marks an unreadable cell. A program is a sequence of colors that repeats from the start of the barcode. It must match every readable cell, and the barcode can end partway through a repetition.
- Part 1 finds the shortest program for each barcode on its own, then adds up those program lengths.
- Part 2 joins all the barcodes in input order and finds the shortest program for the whole sequence. The repeat carries across line breaks.
Part 1. Find each barcode’s shortest program
I started with the same routine for both parts. Try a program of length one, then two, then three, and so on. For each length, go through the readable cells in position order and assign their colors to slots. As soon as two colors land in the same slot, try the next length.
- Baseline
- 1.823ms
Baseline JavaScript
const colors = "roygbv";
function scanBarcodes(input) {
const rows = input.trim().split(/\r\n?|\n/);
function scan(row) {
const codes = Uint8Array.from(row, (color) => colors.indexOf(color) + 1);
const slots = new Uint8Array(codes.length);
for (let p = 1; p <= codes.length; p++) {
slots.fill(0, 0, p);
let i = 0;
for (; i < codes.length; i++) {
const color = codes[i];
if (!color) continue;
const slot = i % p;
if (slots[slot] && slots[slot] !== color) break;
slots[slot] = color;
}
if (i === codes.length) return p;
}
}
const part1 = rows.reduce((sum, row) => sum + scan(row), 0);
return [part1, rows.length === 1 ? part1 : scan(rows.join(""))];
}A two-slot program puts positions 0, 2, and 4 in its first slot. In r?b??r, the red at position 0 and the blue at position 2 would both use that slot. Length two fails because the slot can hold only one color.
-
Slot 0
r0 b2 ?4
-
Slot 1
?1 ?3 r5
Length 2 fails. Slot 0 gets red at 0 and blue at 2.
For a program with p slots, the remainder of position i divided by p gives its slot. This is what folding the barcode means. Compare the readable colors in each slot. If a slot contains only question marks, its program color can be anything.
What a period means when cells are missing
In r?b, a one-slot program puts red and blue in the same slot even though a hole separates them. Compare all readable cells in each slot, including the ones separated by holes. This is the usual period condition for partial words. Blanchet-Sadri, Mandel and Sisodia, Periods in Partial Words: An Algorithm.
Why holes change the usual period rules
In r????b, the two readable positions are five apart. Lengths two and three put them in different slots, so both fit. Length one puts them together and fails, even though one is the greatest common divisor of two and three.
For complete words, the Fine–Wilf theorem would guarantee that common period once the word reached length . Holes change the hypothesis. Fine and Wilf, Uniqueness Theorems for Periodic Functions.
Part 2. Find a period for the joined barcode
The same scan works on the joined barcode. A long red run followed by one blue cell exposes its weakness. Many trials rescan the entire red run before reaching the blue cell that rejects them.
Put a budget on direct trials
I kept the direct scan for short lengths and limited how much work it could do on the others. Once the budget ran out, I needed a way to rule out many lengths from the same evidence. One red-blue pair can reject every length that puts the two cells into the same slot.
- Before
- 1.823ms
- After
- 1.476ms
- Speedup
- 1.24×
Turn a conflict into a forbidden divisor
In r?b??r, blue sits two positions from the first red and three from the last. A length that divides either distance forces one of those pairs into the same slot. That rules out lengths one, two, and three. Four is the first length that divides neither distance.
In general, positions a distance d apart land in the same slot exactly when p divides d. Let Δ contain every distance between two different readable colors. A candidate p is valid exactly when it divides none of those distances. To reconstruct a program, give each slot its agreed color and fill any free slot arbitrarily.
Multiples of a valid period also work. Consecutive lengths can alternate between fitting and failing, so the search still tries lengths in order.
Compute every shift with three correlations
Encode six colors as 1–6 and a hole as 0. Let C be that sequence, K the indicator of a known cell, and Q the elementwise square of C. For a shift d, sum the squared differences of all readable pairs at that separation. Every term is nonnegative, so the sum is zero exactly when nothing conflicts.
For two sequences A and B, write for the cross-correlation that multiplies by and sums over i. Expanding the square turns the energy into three correlations. The mixed term needs no extra copy of K because C is already zero at holes. Squared-difference cancellation is a standard technique in convolution-based wildcard matching. Clifford and Clifford, Simple Deterministic Wildcard Matching.
- EncodeBuild the known mask, colors, and squared colors. Pad each array with zeros.
- CorrelateTransform each array. Multiply at opposite frequency indices and accumulate the three terms.
- Rule out periodsTransform back. For each trial length, look for any nonzero energy at a multiple of it.
Keep the zero test exact
A number-theoretic transform performs Fourier arithmetic in a finite field. Choose the length M to be the next power of two at least 2n − 1. This separates the positive and negative shifts of the original data and prevents wraparound in the required correlation values. Use modulus P and a primitive Mth root of unity ω. Opposite frequency indices implement circular reversal, giving the cross-correlation identity below. The negative index is taken modulo M. J. M. Pollard, The Fast Fourier Transform in a Finite Field.
The solver uses the prime 23,068,673, whose predecessor is , and generator 3. At the solver limit of 524,288 cells, the largest possible coefficient is smaller than the modulus. The integer products and sums also stay below JavaScript’s exact-integer bound.
The correlation is symmetric, so the return transform can reuse the forward routine. Its result differs from the inverse only by the factor M. That factor is invertible modulo P and leaves the zero test intact.
Each frequency and its opposite have the same energy. The loop computes the pair once and writes both positions, reusing the transformed known array for the return transform.
for (let i = 0; i <= size / 2; i++) {
const opposite = (size - i) % size;
const energy = (
squared[i] * known[opposite] + known[i] * squared[opposite] -
2 * color[i] * color[opposite]
) % MODULUS;
known[i] = energy < 0 ? energy + MODULUS : energy;
known[opposite] = known[i];
}
The transforms take O(n log n) arithmetic operations. Testing all candidate lengths examines a harmonic number of multiples, so that step fits the same bound even if it never exits early. Working space is linear. The two-line example below returns 7 for separate barcodes and 4 for the concatenation.
Replace remainder in the butterfly
Every transform butterfly multiplies two residues and reduces their product modulo P. Computing the remainder with % was the expensive operation in that loop. Instead, the solver precomputes 1/P, approximates the quotient with a multiply, and rounds down. To see why this gives the exact remainder, look at how close the quotient can come to an integer.
const INVERSE_MODULUS = 1 / MODULUS;
function multiplyMod(a, b) {
const product = a * b;
return product - Math.floor(product * INVERSE_MODULUS) * MODULUS;
}
The product x = ab is exact because the two input residues are integers in [0, P) and P² < 2⁴⁹. If either residue is zero, the result is zero. Otherwise primality ensures x has a nonzero remainder. The true quotient q = x/P is therefore at least 1/P from either neighboring integer.
The reciprocal and the multiply each round once in binary64. Each rounding gives a relative error of at most the unit roundoff u = 2⁻⁵³. Multiplying the two error factors gives a relative error bound of 2u + u². With q < P, the resulting absolute error is smaller than the gap to either neighboring integer. Nicholas J. Higham, Accuracy and Stability of Numerical Algorithms, ch. 2.
So Math.floor recovers the exact integer quotient, and the final multiply and subtract are exact integer operations too. This proof applies to products of two residues. The signed sum of products in the frequency loop still uses %.
I isolated that change on a generated 64,000-cell barcode that forced the older solver to use the transform. Only the butterflies and root-table entries used the new reduction.
- Before
- 101.15ms
- After
- 44.79ms
- Speedup
- 2.26×
Find collisions sooner
The budget controlled the worst runs, but there was still a lot of ordinary trial work. I tried shuffling the list of readable positions once with a fixed seed. It brought distant positions into the same group of early probes. On Bob’s input, the loop after the first 32 trials went from 607,899 probes in position order to 83,677 with the shuffle. A period still passes only after every readable cell has been checked.
Each slot stores a trial stamp with its color. The stamp lets a new trial reuse the slots without clearing the table. The scan gets up to 64 probes per input character, with a lower budget when there are few readable pairs to enumerate. It checks the budget between trials. Once the budget expires, the solver computes conflict distances and resumes at the first untested length.
An entry whose value is below stamp came from an earlier trial. An entry at or above stamp came from the current trial, so a different packed color means a collision.
for (; period < codes.length && budget > 0; period++) {
const stamp = period << 3;
let i = 0;
for (; i < knownCount; i++) {
const cell = known[i];
const slot = (cell >>> 3) % period;
const color = stamp | (cell & 7);
if (slots[slot] >= stamp && slots[slot] !== color) break;
slots[slot] = color;
}
if (i === knownCount) return period;
budget -= i + 1;
}Compress evenly spaced cells
In r?b?r, every second cell is readable. Keep those cells and you get rbr. The three readable cells at original indices 0, 2, and 4 become consecutive positions. Start with that spacing of two to see how a trial length changes.
For readable positions s, s + g, s + 2g, …, cells d steps apart in the compressed word are gd apart in the barcode. The original length p puts those cells in the same slot when it divides gd. Cancelling the factors that p shares with g gives the equivalent compressed length q.
For a known word of length m, a period q up to m is equivalent to a prefix of length m − q also being a suffix. Such a prefix is called a border. The Knuth–Morris–Pratt prefix table finds the longest border and links to the shorter ones. Every q greater than m also works because the copies no longer overlap. Knuth, Morris, and Pratt, Fast Pattern Matching in Strings.
| Compressed word | Period q | Smallest original p |
|---|---|---|
rbr with border r | 2 | 4 |
rbr with empty border | 3 | 3 |
r?b?r, stride two turns original period four into compressed period two. Original period three stays three and gives each readable color its own slot.To find the smallest original period that acts like q, write p = qh. The formula requires h to divide g and . So h has to include the full power of each prime that divides both q and g. Repeatedly dividing those common factors out of g finds h without factoring either number. The solver tests the compressed periods in ascending order and stops when even q itself reaches the best original period found so far. With stride one, the longest border gives the answer directly.
Turn pairs of runs into intervals
Consider a run of red cells at indices a through b and a later run of blue cells at c through d. Every distance from c − b through d − a has a conflict. The closest endpoints give the minimum, the farthest give the maximum, and moving either endpoint through its run fills every integer in between.
| Indices | Distance |
|---|---|
| 2 to 5 | 3 |
| 1 to 5 or 2 to 6 | 4 |
| 0 to 5 or 1 to 6 | 5 |
| 0 to 6 | 6 |
rrr??bb, two runs mark the whole interval from 3 through 6. The holes between the runs contribute no colors.Add one at the interval’s first distance and subtract one just past its last distance. A single prefix sum then counts how many conflicting intervals cover every distance. The solver can choose between enumerating unequal-color pairs, marking run intervals, and using the transform according to the amount of work each requires.
- Before
- 1.476ms
- After
- 0.822ms
- Speedup
- 1.80×
Compare eight cells with one word
The long-barcode improvements left a lot of tiny rows doing their own trials. I tried answering each short row with one integer. Each readable cell fits in four bits. The low three encode its color and the fourth marks it as readable. A hole has all four bits clear. Shift by four bits per cell to line up pairs at distance d. XOR gives the color difference in each lane, which is zero for equal colors. Adding seven puts any nonzero three-bit difference above seven and keeps every sum below sixteen. That sets the lane’s high bit without carrying into its neighbor.
| Lane | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Original | r | ? | b | ? | r |
| Shifted by 2 | b | ? | r | · | · |
| Clash bit | 1 | 0 | 1 | 0 | 0 |
const differences = ((left ^ right) & 0x77777777) + 0x77777777;
const clashBits = differences & left & right & 0x88888888;
The final AND keeps only differences between readable cells. This is SIMD within a register, using the bits of a single JavaScript integer as eight independent lanes. On rows of up to eight cells, each shift with a clash contributes a precomputed bit mask of its divisors. OR those masks and take the lowest still-clear period bit. Fisher and Dietz, Compiling for SIMD Within a Register.
- Before
- 0.822ms
- After
- 0.308ms
- Speedup
- 2.67×
Try the cheap checks on long barcodes first
I tried the same comparison on long, irregular barcodes before asking for every conflict distance.
For long irregular barcodes, check distances p, 2p, 3p, … for each candidate period p. As soon as a word contains a clash, that distance rules out p. Cache each tested distance for later periods, and combine neighboring words when the shift starts in the middle of a word. If the packed scan uses up its budget, the exact residue scan resumes at the current period.
I also moved interval marking ahead of repeated scans for barcodes with very few runs and raised the pair-enumeration budget for sparse inputs. On a generated 64,000-cell barcode with 60% holes, the packed loop found conflicts fast enough to skip the transform. With 98% holes, enumerating the relatively few readable pairs proved cheaper.
- Before
- 0.308ms
- After
- 0.238ms
- Speedup
- 1.30×
How the solver chooses
- Handle short rows and short periods. Pack rows up to eight cells into one word. On longer rows, try up to length 32, with an early interval calculation when a long row has few pairs of color runs.
- Check the spacing. If the readable cells are evenly spaced, compress them into a word and find its periods.
- Probe the remaining lengths. Compare eight packed pairs at a time where enough cells are readable. Then shuffle the readable cells for the direct scan. Each pass has a work budget.
-
Build the conflict distances. Try these options in order, then resume the search at the first untested length.
- Few unequal pairsList their distances.
- Few pairs of runsMark distance intervals.
- Many pairs either wayCompute every distance with a transform.
Widen the comparisons to sixteen cells
Wasm supports native 64-bit integers inside the solver. The same four-bit cell encoding now fits sixteen cells in a u64, so the one-word divisor mask works on rows up to length sixteen. For long barcodes the same operation checks twice as many positions before moving to the next word.
let difference = ((left ^ right) & 0x7777_7777_7777_7777) + 0x7777_7777_7777_7777;
let conflicts = difference & left & right & 0x8888_8888_8888_8888;
The transform can use exact integer products as well. Two residues multiply to less than P², so the butterfly’s product fits in u64. The bit-reversal permutation uses the reversed bits of the input index, and each butterfly walks two disjoint slices of the same block. WebAssembly Core Specification, numeric instructions.
Estimate the quotient with integer arithmetic
To reduce a product x modulo P, multiply its high bits by a precomputed reciprocal and shift. This is a form of Barrett reduction. Truncating the bottom twelve bits keeps the intermediate multiply within a u64. Paul Barrett, Implementing the Rivest Shamir and Adleman Public Key Encryption Algorithm on a Standard Digital Signal Processor.
let product = u64::from(a) * u64::from(b);
let quotient = ((product >> 12) * RECIPROCAL) >> 38;
let residue = (product - quotient * u64::from(PRIME)) as u32;
if residue >= PRIME { residue - PRIME } else { residue }
Here RECIPROCAL = ⌊2⁵⁰/P⌋. Dropping the low bits and rounding the reciprocal both lower the estimate. Together they lose less than 2¹²/P + P²/2⁵⁰, which is below one. The integer quotient is therefore exact or one too small, and at most one subtraction of P finishes the reduction.
I also cut the direct-trial budget when fewer than one in eight cells are readable. On the generated 64,000-cell barcode with 92% holes, the shorter search and integer reduction together brought the Rust time from 16.5 ms to 13.0 ms in a matched Chromium trial.
- Before
- 0.3969ms
- After
- 0.1219ms
- Speedup
- 3.26×
Benchmarks
| Workload | Adaptive JavaScript | Rust/Wasm |
|---|---|---|
| Bob’s input, fresh worker | 9.3 ms | 7.0 ms |
| Bob’s input, warm solve | 0.397 ms | 0.122 ms |
| 64,000 generated cells with 60% holes, warm solve | 1.11 ms | 0.603 ms |
| 64,000 generated cells with 92% holes, warm solve | 61.0 ms | 13.0 ms |
The browser comparisons use Chromium 147 on a Threadripper 9970X, with Rust 1.100.0 targeting wasm32-unknown-unknown. Each figure is the median of nine measurements. Warm measurements batch complete solves, including input encoding when needed. Fresh measurements include worker startup, loading the solver on localhost, and receiving both answers.
Earlier JavaScript experiments in Bun
The generated workloads isolate cases in which a single technique does most of the work. The earlier hybrid already had shuffled probes, run intervals, and exact transforms.
| Generated workload | Earlier hybrid | Current hybrid | Path that paid off |
|---|---|---|---|
| 16,000 cells in two blocks with a 100-cell gap | 1.94 ms | 0.044 ms | Early run intervals |
| 64,000 scattered cells, 60% holes | 75.67 ms | 0.765 ms | Packed comparisons |
| 64,000 scattered cells, 98% holes | 63.00 ms | 2.13 ms | Enumerate unequal pairs |
Timings are medians of nine warmed-up batches in Bun v1.4.5 on one logical CPU of a Threadripper 9970X. They include parsing and solving both parts, with file reads and process startup outside the measurement.
- Start
- 4.975ms
- Finish
- 0.122ms
- Speedup
- 40.8×
Run the solver
Paste one barcode per line. Use r, o, y, g, b, v for colors and ? for missing cells. Your input stays in this browser.