advent-of-code/2022/rust/src/day3.rs

67 lines
1.5 KiB
Rust
Raw Normal View History

2022-12-02 14:14:02 -06:00
mod common;
2022-12-02 23:19:18 -06:00
use std::collections::HashSet;
2022-12-02 23:37:44 -06:00
use std::iter::FromIterator;
2022-12-02 23:19:18 -06:00
2022-12-02 14:14:02 -06:00
fn main() {
2022-12-02 23:19:18 -06:00
let input = common::day_input(3);
2022-12-02 14:14:02 -06:00
println!("Part 1: {}", part1(&input));
println!("Part 2: {}", part2(&input));
}
2022-12-03 00:35:29 -06:00
fn priority(b: u8) -> i32 {
(b as i32) - if b >= 97 && b <= 122 { 96 } else { 38 }
}
2022-12-02 14:14:02 -06:00
fn part1(input: &str) -> i32 {
2022-12-03 00:35:29 -06:00
input.lines().map(str::as_bytes).fold(0, |r, b| {
let h = b.len() / 2;
r + priority(
*HashSet::<u8>::from_iter((&b[0..h]).iter().cloned())
.intersection(&HashSet::from_iter((&b[h..b.len()]).iter().cloned()))
.next()
.unwrap(),
)
})
2022-12-02 14:14:02 -06:00
}
fn part2(input: &str) -> i32 {
2022-12-03 00:35:29 -06:00
input
.lines()
.collect::<Vec<&str>>()
.chunks_exact(3)
.fold(0, |r, t| {
r + priority(
*t.iter()
.map(|l| HashSet::<u8>::from_iter(l.bytes()))
.reduce(|a, b| HashSet::from_iter(a.intersection(&b).cloned()))
.unwrap()
.iter()
.next()
.unwrap(),
)
})
2022-12-02 14:14:02 -06:00
}
#[cfg(test)]
mod tests {
use super::*;
2022-12-02 23:19:18 -06:00
const TEST_INPUT: &str = "vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw";
2022-12-02 14:14:02 -06:00
#[test]
fn test_part1() {
2022-12-02 23:19:18 -06:00
assert_eq!(part1(TEST_INPUT), 157)
2022-12-02 14:14:02 -06:00
}
#[test]
fn test_part2() {
2022-12-02 23:37:44 -06:00
assert_eq!(part2(TEST_INPUT), 70)
2022-12-02 14:14:02 -06:00
}
}