Day 2: Fulminating Farmland
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
fn parts(input: &str) -> (String, String) { let targets = input.chars().flat_map(|c| "_oygbvr".find(c)).collect_vec(); let part1 = 6 * targets .iter() .tuple_windows() .filter(|(a, b)| b <= a) .count() + targets.last().unwrap(); let part2 = targets.iter().min().unwrap() + 6 * (input.len() - 1); (part1.to_string(), part2.to_string()) }For part 1, I count the number of wrap-arounds as consecutive colors that are not increasing and check the last color to see where mod 6 it ends up. To make this work nicely, I moved the
rto the end of the colors and added a dummy color at the beginning, such that a singlerends up at 6.For part 2, the resulting program would always be a sorted list of colors, in the reverse order of my character list. Most characters will add 6 to the total. Only at the transition between color segments is the distance reduced, and the reduction corresponds exactly to the difference between the color values. Because the program must be sorted, the total reduction is the difference between the first and the last color. And since the sorting order would be the reverse of my character list, I end up with the inverse difference (mod 6) and add it instead of subtracting.
This is so satisfying. My code did pretty much the same thing at about 3 times the length haha. Well done!
That’s a pretty genius way to do it.
I just refactored my code and felt really smart about it, but now I’m sad again… Nice solution!
In the end I edited my solution to solve part 2 in the same way, but in the case that the input does not contain an ‘o’, it should be -4 instead of -5, since the difference between the first and last color would be 2 (and not 1). Similar for more missing letters. But as always the AOC inputs are (seemingly) made with the intent of not hitting such cases.