median blog

Advent of Code 2024 Day 1 - Rust

Part One

There is nothing too outlandish here. I expect these posts will need to be longer as the days progress. Naturally, there will be spoilers.

We start with a set of numbers separated by three spaces representing two lists. We need to compare elements from the left and right lists to determine the sum of the differences between the elements, starting from the smallest in each list.

Parse the list by reading one line at a time and splitting on the whitespace between the two numbers. Store one in a list called Left and another in Right. Once parsed, sort the lists. This sets them up to be compared in order.

    let content = fs::read_to_string("./inputs/day1.txt").expect("Couldn't read input");

    let mut left: Vec<i32> = Vec::new();
    let mut right: Vec<i32> = Vec::new();

    for line in content.lines() {
        let (l, r) = line.split_once("   ").unwrap();
        left.push(l.parse().unwrap());
        right.push(r.parse().unwrap());
    }

Loop through both lists together, summing the difference between the elements in the list. Remember to take the absolute value of the difference to avoid summing negative numbers.

    let mut total = 0;

    left.sort();
    right.sort();

    for (a, b) in zip(left.clone(), right) {
        total += (b - a).abs();
    }

    println!("{:?}", total);

Part Two

We need to count how often each number appears in the right list. By adding a write to our parsing loop, we can store the counts in a HashMap. The first time we see a number, we insert 1; otherwise, we increment the count by 1.

    let mut right_map: HashMap<i32, i32> = HashMap::new();

    for line in content.lines() {
        let (l, r) = line.split_once("   ").unwrap();
        left.push(l.parse().unwrap());
        right.push(r.parse().unwrap());
        right_map
            .entry(r.parse().unwrap())
            .and_modify(|x| *x += 1)
            .or_insert(1);
    }

Now, we loop through the left list and look up each element in the HashMap. If a value is stored, we multiply it by the number and add it to our running sum.

    let mut total_two = 0;

    for v in left.clone() {
        if let Some(x) = right_map.get(&v) {
            total_two += x * v;
        }
    }

    println!("{:?}", total_two);

The complete solution can be found here.