From dc1e4d074d8fc713d11b8216153f93d0d70f4af3 Mon Sep 17 00:00:00 2001 From: Johannes Date: Sat, 14 Dec 2024 17:44:47 +0100 Subject: [PATCH] day 14 make faster --- src/day14.rs | 29 ++++++++++++++++++----------- src/utils/grid.rs | 16 ++++++++++++++++ 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/src/day14.rs b/src/day14.rs index 62c4377..e636825 100644 --- a/src/day14.rs +++ b/src/day14.rs @@ -7,11 +7,13 @@ use std::{ use itertools::Itertools; +use crate::utils::grid::Grid; + pub fn day_main() { let input = read_to_string("input/day14.txt").unwrap(); let input = input.trim(); println!(" part1: {}", part1(input)); - // println!(" part2: {}", part2(input)); + println!(" part2: {}", part2(input)); } type RiddleResult = usize; @@ -77,22 +79,27 @@ fn part2(input: &str) -> RiddleResult { if seen.contains(&robots) { panic!("Loop after {second} rounds, but no christmas tree!"); } + let mut grid: Grid = Grid::from_default(101, 103); seen.insert(robots.clone()); robots.iter_mut().for_each(|((px, py), (vx, vy))| { *px = (*px + width + *vx) % width; *py = (*py + height + *vy) % height; + grid[(*px, *py)] += 1; + if let Some(v) = grid.get_mut((*px + 1, *py)) { + *v += 1 + } + if let Some(v) = grid.get_mut((*px - 1, *py)) { + *v += 1 + } + if let Some(v) = grid.get_mut((*px, *py + 1)) { + *v += 1 + } + if let Some(v) = grid.get_mut((*px, *py - 1)) { + *v += 1 + } }); - if robots - .iter() - .filter(|(s, _)| { - robots - .iter() - .any(|(t, _)| t != s && (t.0.sub(s.0).abs() + t.1.sub(s.1).abs()) <= 2) - }) - .count() - > robots.len() * 70 / 100 - { + if robots.iter().filter(|(s, _)| grid[*s] > 1).count() > robots.len() * 70 / 100 { printr(&robots, width, height); println!("after {} seconds. Press enter to continue or type 'merry christmas' if you can spot a tree!", second + 1); //+1 because we look at it after they have changed let stdin = io::stdin(); diff --git a/src/utils/grid.rs b/src/utils/grid.rs index 0d92e3e..414dee8 100644 --- a/src/utils/grid.rs +++ b/src/utils/grid.rs @@ -4,6 +4,7 @@ use std::{ }; use itertools::Itertools; +use regex::bytes::Replacer; /// A grid structure, indexed by (x, y) tuples. The top-left coordinate is (0, 0). #[derive(Eq, PartialEq, Debug, Clone)] @@ -99,6 +100,21 @@ impl Grid { } } +impl Grid +where + T: Default, +{ + pub fn from_default(width: i64, height: i64) -> Grid { + let mut content: Vec = Vec::with_capacity((width * height) as usize); + content.resize_with((width * height) as usize, Default::default); + Grid { + content_width: width, + content_height: height, + content, + } + } +} + impl Grid { pub fn parse(input: &str) -> Grid { let content_width = input.lines().next().unwrap().len();