|
9 | 9 | //! For part 2 we can determine the final size of the paper by taking the *last* x and y |
10 | 10 | //! coordinates from the fold instructions. It's then faster and more convenient to process |
11 | 11 | //! each point completely and update the final location, than to step through intermediate folds. |
| 12 | +use crate::util::grid::*; |
12 | 13 | use crate::util::hash::*; |
13 | 14 | use crate::util::iter::*; |
14 | 15 | use crate::util::parse::*; |
@@ -61,40 +62,23 @@ pub fn part1(input: &Input) -> usize { |
61 | 62 | /// The output is a multi-line string to allow integration testing. The final dimensions of the |
62 | 63 | /// paper are found from the last `x` and `y` fold coordinates. |
63 | 64 | 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] = '#'; |
87 | 78 | } |
88 | 79 |
|
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() |
98 | 82 | } |
99 | 83 |
|
100 | 84 | /// Fold point at `x` coordinate, doing nothing if the point is to the left of the fold line. |
|
0 commit comments