mirror of
https://github.com/wezm/advent-of-code.git
synced 2024-12-18 10:19:55 +00:00
2023: Day 4, part 2
This commit is contained in:
parent
1a76994a15
commit
3fd3ad8558
1 changed files with 26 additions and 2 deletions
|
@ -10,6 +10,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
|
||||
let mut points = Vec::new();
|
||||
|
||||
let card_count = input.trim().lines().count().try_into()?;
|
||||
let mut copies = vec![0; card_count];
|
||||
for line in input.lines() {
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
|
@ -17,6 +19,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
let (fst, mine) = line.split_once(" | ").ok_or("expected |")?;
|
||||
let (fst, winning) = fst.split_once(": ").ok_or("expected :")?;
|
||||
let (_, card) = fst.split_once(' ').ok_or("expected ' '")?;
|
||||
let card = card
|
||||
.trim()
|
||||
.parse()
|
||||
.ok()
|
||||
.and_then(|n: usize| n.checked_sub(1))
|
||||
.ok_or("invalid card number")?;
|
||||
let mine = mine
|
||||
.split(' ')
|
||||
.filter(|s| !s.is_empty())
|
||||
|
@ -28,14 +36,30 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
.map(|n| n.parse())
|
||||
.collect::<Result<HashSet<u32>, _>>()?;
|
||||
|
||||
let count: u32 = winning.intersection(&mine).count().try_into().unwrap();
|
||||
let count = winning.intersection(&mine).count();
|
||||
if count > 0 {
|
||||
points.push(2_u64.pow(count - 1));
|
||||
points.push(2_u64.pow((count - 1).try_into()?));
|
||||
}
|
||||
|
||||
// part 2 calculations
|
||||
// add the current card to the count
|
||||
copies[card] += 1;
|
||||
let instances = copies[card];
|
||||
|
||||
// add 'count' copies of subsequent cards
|
||||
let next_card = card + 1;
|
||||
(next_card..next_card + count).for_each(|n| {
|
||||
if let Some(entry) = copies.get_mut(n) {
|
||||
*entry += instances;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let total_points: u64 = points.iter().sum();
|
||||
let total_cards: u64 = copies.iter().sum();
|
||||
|
||||
println!("Part 1: {}", total_points);
|
||||
println!("Part 2: {}", total_cards);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue