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

  • obliviousdusk@lemmy.zip
    link
    fedilink
    arrow-up
    9
    ·
    11 hours ago

    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 r to the end of the colors and added a dummy color at the beginning, such that a single r ends 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.

    • mcmodknower@programming.dev
      link
      fedilink
      English
      arrow-up
      2
      ·
      10 hours ago

      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.