
Source: Day 4: Perilous Pier
Full solution for today (spoilers!).
Part 1
Given a list of strings containing letters and wildcards (
?) determine the length of the shortest possible substring that, when repeated, matches the entire string. Sum these lengths.
This is a bit weird of a way to phrase it, but basically you have something like rgbrgbrgb can be created by repeating the string rgb. The same would be true of rgb?gbr??, since ? matches anything.
To solve this, I’m going to use the (now built in? was it always) Rust chunks function on iter. Basically, break a vector into chunks of a given size. Then, write a custom comparison function that checks the strings for equality–ignoring ? characters.
// Custom equality that basically ignores ? and only matches the prefix on diff lengths
fn eqish(a: &[u8], b: &[u8]) -> bool {
for (ac, bc) in a.iter().zip(b.iter()) {
if ac != bc && *ac != b'?' && *bc != b'?' {
return false;
}
}
true
}
#[aoc::register]
fn part1(input: &str) -> impl Into<String> {
let mut total_instructions = 0;
for barcode in input.lines() {
let barcode = barcode.as_bytes();
'length_loop: for length in 1.. {
// Iterate over every pair of 'chunks' of a given length
// If any pair of chunks doesn't match eqishly, this isn't a valid length
for chunk1 in barcode.chunks(length) {
for chunk2 in barcode.chunks(length) {
if !eqish(chunk1, chunk2) {
continue 'length_loop;
}
}
}
log::debug!("{barcode:?} repeats at length {length}");
total_instructions += length;
break;
}
}
total_instructions.to_string()
}
And run it:
$ just run 4
part1: 8064
$ just bench 4
part1: 306.833µs ± 26.328µs [min: 273.584µs, max: 399.375µs, median: 304.583µs]
That’s fairly quick. I expect there are some minor optimizations you could do, but I feel like no matter what you do, I’m not sure how you’re going to be O(n^2) (which this is).
One of the reasons this does run as quickly as it does is that it will fail fast. As soon as you have any proof that a given length won’t work, bail.
Part 2
Combine all of the lines in the input into a single long string (dropping newlines). Calculate the substring length for just this string.
This is the same problem, just bigger (input). If we have a decent algorithm, it should work fine:
#[aoc::register]
fn part2(input: &str) -> impl Into<String> {
// Drop newlines
let barcode: Vec<u8> = input
.as_bytes()
.iter()
.filter(|b| **b != b'\n')
.copied()
.collect();
'length_loop: for length in 1.. {
for chunk1 in barcode.chunks(length) {
for chunk2 in barcode.chunks(length) {
if !eqish(chunk1, chunk2) {
continue 'length_loop;
}
}
}
return length.to_string();
}
unreachable!("infinite loops!");
}
However, let’s go ahead while we’re writing this and put in a slight optimization. Currently, each pair of chunk1 and chunk2 are basically being counted twice, once when chunk1 is earlier in the string and once when it’s later (and we’re also checking the same chunks against each other, which we don’t need to do).
It’s the equivalent of
for i in 0..n {
for j in 0..n {
// Changing this
}
}
for i in 0..n {
for j in (i+1)..n {
// To this
}
}
For this problem, you enumerate to figure out what i is and then skip that many (plus 1 to also avoid comparing to yourself).
#[aoc::register]
fn part2_skip(input: &str) -> impl Into<String> {
let barcode: Vec<u8> = input
.as_bytes()
.iter()
.filter(|b| **b != b'\n')
.copied()
.collect();
// Slight optimization to only compare each pair of chunks once
// Rather than twice with chunk1 vs chunk2 being the 'first' chunk
'length_loop: for length in 1.. {
for (i, chunk1) in barcode.chunks(length).enumerate() {
for chunk2 in barcode.chunks(length).skip(i + 1) {
if !eqish(chunk1, chunk2) {
continue 'length_loop;
}
}
}
return length.to_string();
}
unreachable!("infinite loops!");
}
And that actually really does end up mattering!
$ just run 4
part2: 1640
part2_skip: 1640
$ just bench 4
part2: 1.299674ms ± 56.793µs [min: 1.207833ms, max: 1.460083ms, median: 1.289125ms]
part2_skip: 271.372µs ± 23.1µs [min: 249.416µs, max: 399.084µs, median: 265.083µs]
That’s cutting like 75% of the time. I did also apply that to the part1 above. It’s not quite as dramatic (twice as fast vs 4-5 times), but it’s still a good change to have.
Visualization
Here’s part 1:
Basically, the white box is chunk1 and chunk2 is red or green if it’s a failed or successful match. Takes a bit to render 😄.
Benchmarks
$ just bench 4
part1: 305.49µs ± 25.792µs [min: 275.417µs, max: 420.834µs, median: 296.75µs]
part1_skip: 187.711µs ± 21.255µs [min: 169.542µs, max: 307.292µs, median: 181.042µs]
part2: 1.299674ms ± 56.793µs [min: 1.207833ms, max: 1.460083ms, median: 1.289125ms]
part2_skip: 271.372µs ± 23.1µs [min: 249.416µs, max: 399.084µs, median: 265.083µs]