🏡 index : ~doyle/aoc.git

author Jordan Doyle <jordan@doyle.la> 2024-12-01 11:32:40.0 +00:00:00
committer Jordan Doyle <jordan@doyle.la> 2024-12-01 11:32:49.0 +00:00:00
commit
be1e205000264e06de50fe96754e59e99fa23414 [patch]
tree
6f99b7da6ebff1487b3b79ee82b63ae8ea2928b8
parent
8478a64dc0f5e1b5fdea627d2fea346d28ec84cb
download
be1e205000264e06de50fe96754e59e99fa23414.tar.gz

Add 2024 day 1



Diff

 Cargo.toml |  4 ++++
 2024/01.rs | 41 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 45 insertions(+)

diff --git a/Cargo.toml b/Cargo.toml
index 0f37151..246299a 100644
--- a/Cargo.toml
+++ a/Cargo.toml
@@ -26,6 +26,10 @@
name = "aoc2023-05"
path = "2023/05.rs"

[[bin]]
name = "aoc2024-01"
path = "2024/01.rs"

[profile.release]
overflow-checks = true

diff --git a/2024/01.rs b/2024/01.rs
new file mode 100644
index 0000000..36325c2 100644
--- /dev/null
+++ a/2024/01.rs
@@ -1,0 +1,41 @@
#![feature(binary_heap_into_iter_sorted)]
use std::{cmp::Reverse, collections::BinaryHeap, io::Read};

use itertools::Itertools;

fn main() {
    let mut input = String::new();
    std::io::stdin().read_to_string(&mut input).unwrap();
    let (left, right) = parse_input(&input);
    part1(left.clone(), right.clone());
    part2(left.clone(), right.clone());
}

fn part1(left: BinaryHeap<Reverse<u64>>, right: BinaryHeap<Reverse<u64>>) {
    let res: u64 = left
        .into_iter_sorted()
        .zip(right.into_iter_sorted())
        .map(|(Reverse(l), Reverse(r))| l.abs_diff(r))
        .sum();
    eprintln!("part 1: {res}");
}

fn part2(left: BinaryHeap<Reverse<u64>>, right: BinaryHeap<Reverse<u64>>) {
    let counts = right.into_iter().counts();
    let res: usize = left
        .into_iter()
        .map(|v| v.0 as usize * counts.get(&v).copied().unwrap_or_default())
        .sum();
    eprintln!("part 2: {res}");
}

fn parse_input(input: &str) -> (BinaryHeap<Reverse<u64>>, BinaryHeap<Reverse<u64>>) {
    input.split('\n').filter_map(|v| v.split_once("   ")).fold(
        (BinaryHeap::new(), BinaryHeap::new()),
        |(mut left_acc, mut right_acc), (left, right)| {
            left_acc.push(Reverse(left.parse().unwrap()));
            right_acc.push(Reverse(right.parse().unwrap()));
            (left_acc, right_acc)
        },
    )
}