DEV Community

Cover image for Advent of Code 2023 - DAY 8
Antonio Perrone
Antonio Perrone

Posted on

Advent of Code 2023 - DAY 8

Problem Day 8: Haunted Wasteland

Here the day 8 problem statement: https://adventofcode.com/2023/day/8

Solution Part 1

pub fn part_one(input: &str) -> Option<u32> {
    let commands = input.lines().next().unwrap();

    let mut network: HashMap<&str, (&str, &str)> = HashMap::new();

    input.lines().skip(2).for_each(|line| {
        let parts: Vec<&str> = line.split(" = ").collect();
        let key = parts[0];
        let value = parts[1]
            .strip_prefix('(')
            .unwrap()
            .strip_suffix(')')
            .unwrap()
            .split_once(", ")
            .unwrap();
        network.insert(key, value);
    });

    let mut step = network.get("AAA").unwrap();
    let mut counter = 0;

    for command in commands.chars().cycle() {
        counter += 1;
        if command == 'L' {
            if step.0 == "ZZZ" {
                return Some(counter);
            }
            let next = network.get(step.0).unwrap();

            step = next;
        } else if command == 'R' {
            if step.1 == "ZZZ" {
                return Some(counter);
            }
            let next = network.get(step.1).unwrap();
            step = next;
        }
    }

    Some(counter)
}
Enter fullscreen mode Exit fullscreen mode

Solution Part 2

fn lcm(nums: &[usize]) -> usize {
    let mut result = 1;
    for &num in nums {
        result = num * result / gcd(num, result);
    }
    result
}

fn gcd(a: usize, b: usize) -> usize {
    if b == 0 {
        return a;
    }

    gcd(b, a % b)
}

pub fn part_two(input: &str) -> Option<usize> {
     let commands = input.lines().next().unwrap();

    let mut network: HashMap<&str, (&str, &str)> = HashMap::new();

    input.lines().skip(2).for_each(|line| {
        let parts: Vec<&str> = line.split(" = ").collect();
        let key = parts[0];
        let value = parts[1]
            .strip_prefix('(')
            .unwrap()
            .strip_suffix(')')
            .unwrap()
            .split_once(", ")
            .unwrap();
        network.insert(key, value);
    });

    let start_nodes: Vec<_> = network.iter().filter(|x| x.0.ends_with('A')).collect();

    let mut end_counts = HashMap::<&str, usize>::new();

    for start in start_nodes.iter() {
        let mut current_node_name = *start.0;
        let mut count = 0;
        let mut commands_list = commands.chars().cycle();

        while !current_node_name.ends_with('Z') {
            let command = commands_list.next().unwrap();
            let current_node = network.get(current_node_name).unwrap();

            let next_node_name = match command {
                'L' => current_node.0,
                'R' => current_node.1,
                _ => unreachable!(),
            };

            current_node_name = next_node_name;
            count += 1;
        }

        end_counts.insert(start.0, count);
    }

    let counts = end_counts.values().cloned().collect::<Vec<_>>();

    let lcm = lcm(&counts);

    Some(lcm)
}
Enter fullscreen mode Exit fullscreen mode

Here the repository with all puzzle solutions.

Top comments (0)