Day 3: Gear Ratios


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)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ or pastebin (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


🔒This post will be unlocked when there is a decent amount of submissions on the leaderboard to avoid cheating for top spots

🔓 Edit: Post has been unlocked after 11 minutes

  • capitalpb@programming.dev
    link
    fedilink
    English
    arrow-up
    2
    ·
    7 months ago

    Another day of the 2023 Advent of Code, and another day where I hate looking at my code. This year just seems like it is starting off a lot more complex than I remember in previous years. This one was a little tricky, but I got there without any major setbacks. Another one I am excited to come back to and clean up, but this first pass is all about getting a solution, and this one works.

    https://github.com/capitalpb/advent_of_code_2023/blob/main/src/solvers/day03.rs

    #[derive(Clone, Copy, Debug)]
    struct Location {
        row: usize,
        start_col: usize,
        end_col: usize,
    }
    
    #[derive(Debug)]
    struct EngineSchematic {
        schematic: Vec>,
        numbers: Vec,
        symbols: Vec,
    }
    
    impl EngineSchematic {
        fn from(input: &str) -> EngineSchematic {
            let schematic: Vec> = input.lines().map(|line| line.chars().collect()).collect();
            let mut numbers = vec![];
            let mut symbols = vec![];
            let mut location: Option = None;
    
            for (row_index, row) in schematic.iter().enumerate() {
                for (col, ch) in row.iter().enumerate() {
                    match ch {
                        ch if ch.is_ascii_punctuation() => {
                            if let Some(location) = location {
                                numbers.push(location);
                            }
                            location = None;
    
                            if ch != &'.' {
                                symbols.push(Location {
                                    row: row_index,
                                    start_col: col,
                                    end_col: col,
                                });
                            }
                        }
                        ch if ch.is_digit(10) => {
                            if let Some(mut_location) = location.as_mut() {
                                mut_location.end_col = col;
                            } else {
                                location = Some(Location {
                                    row: row_index,
                                    start_col: col,
                                    end_col: col,
                                });
                            }
                        }
                        _ => {
                            unreachable!("malformed input");
                        }
                    }
                }
    
                if let Some(location) = location {
                    numbers.push(location);
                }
                location = None;
            }
    
            EngineSchematic {
                schematic,
                numbers,
                symbols,
            }
        }
    
        fn get_number_value(&self, location: &Location) -> u32 {
            self.schematic[location.row][location.start_col..=location.end_col]
                .iter()
                .collect::()
                .parse::()
                .unwrap()
        }
    
        fn is_gear(&self, location: &Location) -> bool {
            self.schematic[location.row][location.start_col] == '*'
        }
    
        fn are_adjacent(&self, location: &Location, other_location: &Location) -> bool {
            location.start_col >= other_location.start_col.checked_sub(1).unwrap_or(0)
                && location.end_col <= other_location.end_col + 1
                && (location.row == other_location.row
                    || location.row == other_location.row.checked_sub(1).unwrap_or(0)
                    || location.row == other_location.row + 1)
        }
    }
    
    pub struct Day03;
    
    impl Solver for Day03 {
        fn star_one(&self, input: &str) -> String {
            let schematic = EngineSchematic::from(input);
    
            schematic
                .numbers
                .iter()
                .filter(|number| {
                    schematic
                        .symbols
                        .iter()
                        .any(|symbol| schematic.are_adjacent(symbol, number))
                })
                .map(|number| schematic.get_number_value(number))
                .sum::()
                .to_string()
        }
    
        fn star_two(&self, input: &str) -> String {
            let schematic = EngineSchematic::from(input);
    
            schematic
                .symbols
                .iter()
                .filter(|symbol| schematic.is_gear(symbol))
                .map(|symbol| {
                    let adjacent_numbers = schematic
                        .numbers
                        .iter()
                        .filter(|number| schematic.are_adjacent(symbol, number))
                        .collect::>();
                    if adjacent_numbers.len() == 2 {
                        schematic.get_number_value(adjacent_numbers[0])
                            * schematic.get_number_value(adjacent_numbers[1])
                    } else {
                        0
                    }
                })
                .sum::()
                .to_string()
        }
    }