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

79 lines
1.9 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));
}
fn part1(input: &str) -> i32 {
2022-12-02 23:19:18 -06:00
let mut r = 0_i32;
for l in input.lines() {
println!("{}", l);
let mut s: HashSet<u8> = HashSet::new();
let bytes = l.as_bytes();
let mut n = 0;
let bar = bytes.len() / 2;
println!("{}", bar);
for b in bytes {
print!("{}.", b);
if s.contains(b) && n >= bar {
if *b >= 97 && *b <= 122 {
r += (*b as i32) - 96;
} else {
r += (*b as i32) - 65 + 27;
}
println!(" == {}", r);
break;
} else if n < bar {
s.insert(*b);
}
n += 1
}
}
2022-12-02 23:37:44 -06:00
r
2022-12-02 14:14:02 -06:00
}
fn part2(input: &str) -> i32 {
2022-12-02 23:37:44 -06:00
let mut r = 0_i32;
for t in input.lines().collect::<Vec<&str>>().chunks_exact(3) {
let a: HashSet<u8> = HashSet::from_iter(t[0].bytes());
let b: HashSet<u8> = HashSet::from_iter(t[1].bytes());
let c: HashSet<u8> = HashSet::from_iter(t[2].bytes());
let ab = HashSet::from_iter(a.intersection(&b).cloned());
let b = ab.intersection(&c).next().unwrap();
if *b >= 97 && *b <= 122 {
r += (*b as i32) - 96;
} else {
r += (*b as i32) - 65 + 27;
}
println!("+{} = {}", b, r);
}
r
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
}
}