struct Puzzle {
map: HashMap<(i32, i32), char>,
+ rolls: usize,
}
impl Puzzle {
.filter(|(_, c)| *c == '@')
.for_each(|(j, c)| { map.insert((i as i32, j as i32), c); });
});
- Puzzle { map: map }
+ Puzzle { map: map, rolls: 0 }
}
- fn part1(&self) -> usize {
- self.map.iter().filter(|((i,j), _)| {
+ fn count_and_remove(&mut self) -> usize {
+ let mut rolls: Vec<(i32, i32)> = Vec::new();
+ let c = self.map.iter().filter(|((i,j), _)| {
let c = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)].into_iter()
.filter(|(dx,dy)| self.map.contains_key(&(i+dx, j+dy)))
.count();
- //println!(" (i,j): {} {} - {}", i, j, c);
- //println!("{}, {}", i, j);
c < 4
})
- .count()
+ .map(|(key, _)| {
+ rolls.push(*key);
+ 1
+ })
+ .count();
+ rolls.into_iter().for_each(|key| { self.map.remove(&key); });
+ self.rolls += c;
+ c
+ }
+ fn part1(&mut self) -> usize {
+ self.count_and_remove()
+ }
+
+ fn part2(&mut self) -> usize {
+ let mut c = self.count_and_remove();
+ while c > 0 {
+ c = self.count_and_remove();
+ }
+ self.rolls
}
}
pub fn run(input: &str) -> Result<(), Box<dyn Error>> {
- let p = Puzzle::new(input);
+ let mut p = Puzzle::new(input);
println!("part1: {}", p.part1());
+ println!("part2: {}", p.part2());
Ok(())
}
#[test]
fn test_part1() {
- assert_eq!(Puzzle::new(INPUT).part1(), 13);
+ assert_eq!(13, Puzzle::new(INPUT).part1());
+ }
+ #[test]
+ fn test_part2() {
+ assert_eq!(43, Puzzle::new(INPUT).part2());
}
}