dumb_shit/2022-aoc/src/d3.rs

59 lines
1.5 KiB
Rust
Raw Normal View History

2022-12-04 00:15:56 +00:00
use std::collections::HashSet;
2022-12-03 23:06:01 +00:00
use aoc_runner_derive::{aoc as aoc_run, aoc_generator};
type Contents = (HashSet<char>, HashSet<char>);
fn get_priority(item: &char) -> u32 {
2022-12-04 00:15:56 +00:00
if item.is_ascii_lowercase() {
2022-12-03 23:06:01 +00:00
*item as u32 - 96
} else {
*item as u32 - 38
}
}
#[aoc_generator(day3, part1)]
fn parse_input(input: &str) -> Vec<Contents> {
let mut out = Vec::with_capacity(input.len());
for line in input.lines() {
let half_len = line.len() / 2;
let lo = HashSet::from_iter(line[0..half_len].chars());
let hi = HashSet::from_iter(line[half_len..].chars());
out.push((lo, hi));
}
out
}
2022-12-04 00:15:56 +00:00
#[aoc_generator(day3, part2)]
fn parse_input2(input: &str) -> Vec<u32> {
let mut out = Vec::with_capacity(input.len() / 3);
let lines: Vec<&str> = input.lines().collect();
for group in lines.chunks_exact(3) {
let [x, y, z] = group else {panic!()};
let x: HashSet<char> = HashSet::from_iter(x.chars());
let y = HashSet::from_iter(y.chars());
let z = HashSet::from_iter(z.chars());
let xy: HashSet<char> = x.intersection(&y).copied().collect();
let common = xy.intersection(&z).next().unwrap();
out.push(get_priority(common));
}
out
}
2022-12-03 23:06:01 +00:00
#[aoc_run(day3, part1)]
fn part1(sacks: &[Contents]) -> u32 {
let mut out = 0;
2022-12-04 00:15:56 +00:00
for (lo, hi) in sacks {
let common = lo.intersection(hi).next().unwrap();
2022-12-03 23:06:01 +00:00
out += get_priority(common);
}
out
}
2022-12-04 00:15:56 +00:00
#[aoc_run(day3, part2)]
fn p2(items: &[u32]) -> u32 {
items.iter().sum()
}