diff --git a/src/bin/day18.rs b/src/bin/day18.rs index 8914973..5318213 100644 --- a/src/bin/day18.rs +++ b/src/bin/day18.rs @@ -7,7 +7,7 @@ type Output1 = usize; type Output2 = Output1; struct Step { - direction: Vector2D, + _direction: (isize, isize), count: isize, color: String, } @@ -18,11 +18,11 @@ impl FromStr for Step { fn from_str(s: &str) -> Result { let mut parts = s.split_ascii_whitespace(); - let direction = match parts.next().unwrap() { - "U" => Vector2D::new(0, -1), - "D" => Vector2D::new(0, 1), - "L" => Vector2D::new(-1, 0), - "R" => Vector2D::new(1, 0), + let _direction = match parts.next().unwrap() { + "U" => (0, -1), + "D" => (0, 1), + "L" => (-1, 0), + "R" => (1, 0), _ => unreachable!(), }; @@ -34,13 +34,19 @@ impl FromStr for Step { .to_owned(); Ok(Step { - direction, + _direction, count, color, }) } } +impl Step { + fn direction(&self) -> Vector2D { + Vector2D::new(self._direction.0, self._direction.1) + } +} + fn flood_fill(m: &mut [Vec], start: Vector2D, original: char, fill: char) -> usize { let mut filled_in = 0; @@ -75,22 +81,46 @@ impl Solution for Day18 { } fn part_1(&mut self) -> Output1 { - let n = self.plan.iter().map(|s| s.count).sum::(); + let (min_x, max_x, min_y, max_y) = self.plan.iter().fold((0, 0, 0, 0), |dimensions, s| { + let (mut lx, mut ux, mut ly, mut uy) = dimensions; - let mut map = vec![vec!['.'; 2 * n as usize]; 2 * n as usize]; - let mut position = Vector2D::new(n, n); + match s._direction { + (0, 1) => uy += s.count, + (0, -1) => ly += s.count, + (1, 0) => ux += s.count, + (-1, 0) => lx += s.count, + _ => unreachable!(), + } + (lx, ux, ly, uy) + }); + let (width, height) = (min_x + max_x + 1, min_y + max_y + 1); + + debug!("Dimensions: {}×{}", width, height); + + let mut map = vec![vec!['.'; width as usize]; height as usize]; + let mut position = Vector2D::new(min_x, min_y); + // debug!("Initial position: {:?}", position); + + // let (mut min_x, mut max_x, mut min_y, mut max_y) = (isize::MAX, isize::MIN, isize::MAX, isize::MIN); for s in &self.plan { + let direction = s.direction(); for _ in 0..s.count { + // min_x = std::cmp::min(min_x, position.x()); + // max_x = std::cmp::max(max_x, position.x()); + // min_y = std::cmp::min(min_y, position.y()); + // max_y = std::cmp::max(max_y, position.y()); + map[position] = '#'; - position = position + s.direction; + position = position + direction; } } + // debug!("x ∈ ⟨{} ; {}⟩\ty ∈ ⟨{} ; {}⟩", min_x, max_x, min_y, max_y); flood_fill(&mut map, Vector2D::new(0, 0), '.', '+'); while let Some((y, x)) = - iproduct!(0..2 * n as usize, 0..2 * n as usize).find(|&(y, x)| map[y][x] == '.') + iproduct!(0..height as usize, 0..width as usize).find(|&(y, x)| map[y][x] == '.') { flood_fill(&mut map, Vector2D::new(x as isize, y as isize), '.', '#'); }