From 99b0fd06becfd181f805e4ca55d2b1923a3105c3 Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Sat, 9 Dec 2023 11:34:19 -0600 Subject: [PATCH] Day 4 part 2 brute force --- 2023/rust/src/day4.rs | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/2023/rust/src/day4.rs b/2023/rust/src/day4.rs index 0444667..c02e637 100644 --- a/2023/rust/src/day4.rs +++ b/2023/rust/src/day4.rs @@ -9,7 +9,10 @@ use nom::{ sequence::tuple, IResult, }; -use std::{collections::HashSet, iter::FromIterator}; +use std::{ + collections::{HashMap, HashSet}, + iter::FromIterator, +}; use crate::prelude::*; @@ -25,11 +28,14 @@ struct Card { } impl Card { + fn num_winning(&self) -> usize { + self.has.iter().filter(|n| self.winning.contains(n)).count() as usize + } + fn points(&self) -> usize { - let num_winning = self.has.iter().filter(|n| self.winning.contains(n)).count() as u32; - println!("{self:?} num_winning -> {num_winning}"); - if num_winning >= 1 { - 2_u64.pow(num_winning - 1) as usize + let n = self.num_winning(); + if n >= 1 { + 2_u64.pow((n - 1) as u32) as usize } else { 0 } @@ -60,7 +66,27 @@ impl AoCSolution for Day4 { } fn part2(input: Self::Input) -> Self::Solution { - 0 + let mut result = 0; + let mut copies: HashMap = HashMap::new(); + input.lines().for_each(|s| { + let card = card(s).unwrap().1; + println!("{}, cur result: {}", card.id, result); + let mut num_copies = 1; + if let Some(extra_copies) = copies.get(&card.id) { + num_copies += extra_copies; + } + for _ in 1..=num_copies { + for i in card.id..=(card.id + card.num_winning()) { + if let Some(n) = copies.get_mut(&i) { + *n += 1; + } else { + copies.insert(i, 1); + } + } + } + result += num_copies + }); + result } } @@ -78,6 +104,6 @@ Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36 Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11"#; println!("input:\n{input}"); assert_eq!(Day4::part1(input.into()), 13); - assert_eq!(Day4::part2(input.into()), 0); + assert_eq!(Day4::part2(input.into()), 30); } }