Day 4: Perilous Pier
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465


Rust
Same basic algorithm as @addie@feddit.uk’s C++ solution, probably the same off-by-one during development too. Use the input
orbif you pass the tests of part 1, but not the real input. The output should help you find the problem in your code. (I only found it after reading addie’s part 1 solution.)Its testing each prefix of the barcode, starting with the smallest and stopping as soon as it found a match. During matching,
?symbols in the pattern are replaced with the characters from the barcode, and modulo is used to repeat the pattern. My implementation doesn’t copy chars as often as addie’s, but that shouldn’t make much of a difference during runtime.Code
use std::fs; fn main() { run(&fs::read_to_string("../../inputs/2026/4") .expect("Could not read input file")); // println!("expected p1: {}", 3); // run("orb"); } fn run(contents: &str) { let mut sum = 0; for liner in contents.lines() { sum += fun_name(liner); } println!("p1: {}", sum); let c = contents.replace('\n', ""); println!("p2: {}", fun_name(&c)); } fn fun_name(liner: &str) -> usize { let line: Vec<_> = liner.chars().collect(); for l in 1..=line.len() { if check(&line[0..l], &line) { return l; } } panic!(); } fn check(pattern: &[char], line: &Vec<char>) -> bool { let mut p = Vec::with_capacity(pattern.len()); p.extend_from_slice(pattern); let plen = p.len(); for i in 0..line.len() { if p[i%plen] == line[i] { continue; } if p[i%plen] == '?' { p[i%plen] = line[i]; continue; } if line[i] == '?' { continue; } // now both the pattern and the line are different and contain no ? at this pos return false; } // viz // let mut l1 = "#".to_owned(); // let mut l2 = " ".to_owned(); // for i in 0..line.len() { // if i > 0 && i%plen == 0{ // l1.push('|'); // l2.push('|'); // } // l1.push(p[i%plen]); // l2.push(line[i]); // } // println!("{}\n{}", l1, l2); true }