Day 5: Cafeteria
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


Well, I guess I’ve decided to do AoC this year. Trivial problem, though I shamelessly stole some range-merging code from AoC 2022 (it was when I was still well in the learning phase of Rust). If you can’t look at old code and wonder WTF you were thinking, have you really gotten any better?
Solution (mostly uninteresting)
pub fn day05(input: &str) -> (u64, u64) { let mut part1 = 0; let mut part2 = 0; let mut ranges = Vec::new(); let mut lines = input.trim().lines(); for line in lines.by_ref() { if line.is_empty() { break; } let range = line .split_once('-') .map(|(l, h)| [l.parse::<u64>().unwrap(), h.parse::<u64>().unwrap()]) .unwrap(); ranges.push(range); } let ranges = combine_ranges(ranges); for idx in lines { for r in ranges.iter() { if (r[0]..=r[1]).contains(&idx.parse::<u64>().unwrap()) { part1 += 1; break; } } } for r in ranges { part2 += r[1] - r[0] + 1; } (part1, part2) }combine_rangesWARNING : Hideous, triggers Clippy, not blazingly fastfn combine_ranges(ranges: Vec<[u64; 2]>) -> Vec<[u64; 2]> { let mut temp_ranges = ranges; let mut comp_ranges: Vec<[u64; 2]> = Vec::new(); let mut run_again: bool = true; while run_again { run_again = false; comp_ranges = Vec::new(); 'outer: for i in 0..temp_ranges.len() { for j in 0..comp_ranges.len() { if temp_ranges[i][0] <= comp_ranges[j][0] && comp_ranges[j][1] <= temp_ranges[i][1] { //temp covers all of comp comp_ranges[j][0] = temp_ranges[i][0]; comp_ranges[j][1] = temp_ranges[i][1]; run_again = true; continue 'outer; } else if comp_ranges[j][0] <= temp_ranges[i][0] && temp_ranges[i][1] <= comp_ranges[j][1] { //comp covers all of temp run_again = true; continue 'outer; } else if temp_ranges[i][0] <= comp_ranges[j][0] && comp_ranges[j][0] <= temp_ranges[i][1] && temp_ranges[i][1] <= comp_ranges[j][1] { //grow left comp_ranges[j][0] = temp_ranges[i][0]; run_again = true; continue 'outer; } else if comp_ranges[j][0] <= temp_ranges[i][0] && temp_ranges[i][0] <= comp_ranges[j][1] && comp_ranges[j][1] <= temp_ranges[i][1] { //grow right comp_ranges[j][1] = temp_ranges[i][1]; run_again = true; continue 'outer; } } comp_ranges.push(temp_ranges[i]); } temp_ranges = comp_ranges.clone(); } comp_ranges }