Advent of Code (2024)

Rust solutions for AOC 2024


Contents


Day 1

//! Author: https://github.com/dhruvildave

use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::collections::HashMap;

fn part1() {
    let mut l = BinaryHeap::new();
    let mut r = BinaryHeap::new();

    include_str!("file.txt").split('\n').for_each(|i| {
        let line = i
            .split_whitespace()
            .map(|i| i.parse::<u64>().unwrap())
            .collect::<Vec<_>>();

        if line.len() == 2 {
            l.push(Reverse(line[0]));
            r.push(Reverse(line[1]));
        }
    });

    let mut d = 0;

    while !l.is_empty() && !r.is_empty() {
        let a = l.pop().unwrap().0;
        let b = r.pop().unwrap().0;

        d += u64::abs_diff(a, b);
    }

    println!("{d}");
}

fn part2() {
    let mut l = Vec::new();
    let mut r = HashMap::new();

    include_str!("file.txt").split('\n').for_each(|i| {
        let line = i
            .split_whitespace()
            .map(|i| i.parse::<u64>().unwrap())
            .collect::<Vec<_>>();

        if line.len() == 2 {
            l.push(line[0]);
            r.entry(line[1]).and_modify(|i| *i += 1_u64).or_insert(1);
        }
    });

    let d = l.iter().map(|i| r.get(i).unwrap_or(&0) * i).sum::<u64>();

    println!("{d}");
}

fn main() {
    part1();
    part2();
}