Skip to content

Commit 8c933a5

Browse files
committed
Tidy by using fold on the folds
1 parent 4aa8b72 commit 8c933a5

File tree

1 file changed

+16
-32
lines changed

1 file changed

+16
-32
lines changed

src/year2021/day13.rs

Lines changed: 16 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
//! For part 2 we can determine the final size of the paper by taking the *last* x and y
1010
//! coordinates from the fold instructions. It's then faster and more convenient to process
1111
//! each point completely and update the final location, than to step through intermediate folds.
12+
use crate::util::grid::*;
1213
use crate::util::hash::*;
1314
use crate::util::iter::*;
1415
use crate::util::parse::*;
@@ -61,40 +62,23 @@ pub fn part1(input: &Input) -> usize {
6162
/// The output is a multi-line string to allow integration testing. The final dimensions of the
6263
/// paper are found from the last `x` and `y` fold coordinates.
6364
pub fn part2(input: &Input) -> String {
64-
let mut width = 0;
65-
let mut height = 0;
66-
67-
for &fold in &input.folds {
68-
match fold {
69-
Fold::Horizontal(x) => width = x,
70-
Fold::Vertical(y) => height = y,
71-
}
72-
}
73-
74-
let mut grid = vec![false; (width * height) as usize];
75-
76-
for point in &input.points {
77-
let mut point = *point;
78-
79-
for &fold in &input.folds {
80-
point = match fold {
81-
Fold::Horizontal(x) => fold_horizontal(x, point),
82-
Fold::Vertical(y) => fold_vertical(y, point),
83-
}
84-
}
85-
86-
grid[(point.y * width + point.x) as usize] = true;
65+
let (width, height) = input.folds.iter().fold((0, 0), |(width, height), &fold| match fold {
66+
Fold::Horizontal(x) => (x, height),
67+
Fold::Vertical(y) => (width, y),
68+
});
69+
70+
let mut grid = Grid::new(width + 1, height, '.');
71+
72+
for &start in &input.points {
73+
let end = input.folds.iter().fold(start, |point, &fold| match fold {
74+
Fold::Horizontal(x) => fold_horizontal(x, point),
75+
Fold::Vertical(y) => fold_vertical(y, point),
76+
});
77+
grid[end + RIGHT] = '#';
8778
}
8879

89-
let mut code = String::new();
90-
for y in 0..height {
91-
code.push('\n');
92-
for x in 0..width {
93-
let c = if grid[(y * width + x) as usize] { '#' } else { '.' };
94-
code.push(c);
95-
}
96-
}
97-
code
80+
(0..height).for_each(|y| grid[Point::new(0, y)] = '\n');
81+
grid.bytes.iter().collect()
9882
}
9983

10084
/// Fold point at `x` coordinate, doing nothing if the point is to the left of the fold line.

0 commit comments

Comments
 (0)