This commit is contained in:
timeshifter
2024-02-02 18:01:55 +01:00
parent 331f16786c
commit 3eb08f9822
5 changed files with 334 additions and 0 deletions
+86
View File
@@ -0,0 +1,86 @@
use std::collections::HashSet;
use itertools::Itertools;
fn main() {
let cards = aoc::read_file("input.txt")
.into_iter()
.map(Card::from_line)
.collect_vec();
part_a(&cards);
part_b(&cards);
}
fn part_a(cards: &[Card]) {
let mut sum = 0;
for card in cards {
let count = card.winning.intersection(&card.have).count() as u32;
if count == 0 {
continue;
}
let value = 2_usize.pow(count - 1);
sum += value;
}
println!("{sum}");
}
fn part_b(cards: &[Card]) {
let mut result = 0;
let mut register = vec![0_usize; cards.len()];
for card in cards.iter() {
let mut card_count = card.matching_numbers_count();
let additional_counts = 1 + register.pop().unwrap();
let mut j = 0;
let length = register.len();
while card_count != 0 {
register[length - j - 1] += additional_counts;
card_count -= 1;
j += 1;
}
result += additional_counts;
}
println!("{result}");
}
struct Card {
winning: HashSet<u8>,
have: HashSet<u8>,
}
impl Card {
fn new(winning: HashSet<u8>, have: HashSet<u8>) -> Self {
Self { winning, have }
}
fn from_line(line: String) -> Self {
let stripped = line.split_once(':').unwrap().1;
let (winning_raw, have_raw) = stripped.split_once('|').unwrap();
let winning = process_raw_numbers(winning_raw);
let have = process_raw_numbers(have_raw);
Self::new(winning, have)
}
fn matching_numbers_count(&self) -> usize {
self.winning.intersection(&self.have).count()
}
}
fn process_raw_numbers(numbers: &str) -> HashSet<u8> {
numbers
.split_whitespace()
.map(|number| number.parse().unwrap())
.collect()
}