1
0
Fork 0

day(18): make the guess of dimensions better

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2023-12-18 16:26:54 +01:00
parent aa100460a2
commit 4ce1f28556
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -7,7 +7,7 @@ type Output1 = usize;
type Output2 = Output1;
struct Step {
direction: Vector2D<isize>,
_direction: (isize, isize),
count: isize,
color: String,
}
@ -18,11 +18,11 @@ impl FromStr for Step {
fn from_str(s: &str) -> Result<Self, Self::Err> {
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<isize> {
Vector2D::new(self._direction.0, self._direction.1)
}
}
fn flood_fill(m: &mut [Vec<char>], start: Vector2D<isize>, original: char, fill: char) -> usize {
let mut filled_in = 0;
@ -75,22 +81,46 @@ impl Solution<Output1, Output2> for Day18 {
}
fn part_1(&mut self) -> Output1 {
let n = self.plan.iter().map(|s| s.count).sum::<isize>();
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), '.', '#');
}