Loading lizard...


Managed to do it before midnight.


Part 1:

use std::collections::BTreeSet;
use std::io::stdin;
use itertools::Itertools;

type Priority = u32;
type ItemSet = BTreeSet<Priority>;
type Compartment = Vec<Priority>;

fn to_priority(c: char) -> Priority {
    match c {
        'a'..='z' => (c as u32) - 'a' as u32 + 1,
        'A'..='Z' => (c as u32) - 'A' as u32 + 27,
        _ => panic!("Invalid item!")
    }
}

fn main() {
    let sum = stdin().lines().flatten().map(|line| {
        let compartments: Compartment = line.chars().map(to_priority).collect();
        let (left, right) = compartments.split_at(compartments.len()/2);
        let left = BTreeSet::from_iter(left.into_iter());
        let right = BTreeSet::from_iter(right.into_iter());

        let both: Vec<_> = left.intersection(&right).cloned().collect();
        let item = both.get(0).unwrap();
        *item.clone()
    }).sum::<u32>();
    println!("{sum}");
}

Part 2

use std::collections::BTreeSet;
use std::io::stdin;
use itertools::Itertools;

type Priority = u32;
type ItemSet = BTreeSet<Priority>;
type Compartment = Vec<Priority>;

fn to_priority(c: char) -> Priority {
    match c {
        'a'..='z' => (c as u32) - 'a' as u32 + 1,
        'A'..='Z' => (c as u32) - 'A' as u32 + 27,
        _ => panic!("Invalid item!")
    }
}

fn main() {
    let sum = stdin().lines().flatten()
        .map(|line| line.chars().map(to_priority).collect())
        .map(|prios: Compartment| BTreeSet::from_iter(prios))
        .tuples()
        .map(|(elf1, elf2, elf3)| elf1
            .intersection(&elf2)
            .cloned()
            .collect::<ItemSet>()
            .intersection(&elf3)
            .next()
            .unwrap()
            .clone()
        )
        .sum::<Priority>();
    println!("{sum}");
}

You must log in to comment.