|
1 | 1 | #![feature(test)] |
2 | 2 |
|
3 | 3 | use advent_lib::{ |
4 | | - geometry::{vector2, Point, Vector}, |
| 4 | + geometry::{Point, Vector}, |
5 | 5 | grid::Grid, |
6 | 6 | lines::LineSegment, |
7 | 7 | *, |
@@ -31,37 +31,44 @@ impl Iterator for LineIterator { |
31 | 31 |
|
32 | 32 | fn iter(line: &Line) -> LineIterator { |
33 | 33 | LineIterator { |
34 | | - line: line.clone(), |
35 | | - next: Some(line.start.clone()), |
36 | | - step: { |
37 | | - let direction = line.end - line.start; |
38 | | - vector2(direction.x().signum(), direction.y().signum()) |
39 | | - }, |
| 34 | + line: *line, |
| 35 | + next: Some(line.start), |
| 36 | + step: (line.end - line.start).signum(), |
40 | 37 | } |
41 | 38 | } |
42 | 39 |
|
43 | 40 | fn is_horizontal_or_vertical(line: &Line) -> bool { |
44 | 41 | line.start.x() == line.end.x() || line.start.y() == line.end.y() |
45 | 42 | } |
46 | 43 |
|
| 44 | +fn write_line_to(grid: &mut Grid<u8>, line: &LineSegment<2, i32>) { |
| 45 | + for point in iter(line) { |
| 46 | + if let Some(e) = grid.get_mut(point) { |
| 47 | + *e += 1; |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | + |
47 | 52 | fn calculate_part1(input: &Vec<Line>) -> u64 { |
48 | | - let mut grid = Grid::<u8>::new_empty(1000, 1000); |
| 53 | + let mut grid = Grid::<u8>::new_empty( |
| 54 | + input.iter().map(|l| l.max_x()).max().unwrap() + 1, |
| 55 | + input.iter().map(|l| l.max_y()).max().unwrap() + 1, |
| 56 | + ); |
49 | 57 | for line in input { |
50 | 58 | if is_horizontal_or_vertical(line) { |
51 | | - for point in iter(line) { |
52 | | - grid.get_mut(point).map(|e| *e += 1); |
53 | | - } |
| 59 | + write_line_to(&mut grid, line); |
54 | 60 | } |
55 | 61 | } |
56 | 62 | grid.entries().filter(|(_, &value)| value >= 2).count() as u64 |
57 | 63 | } |
58 | 64 |
|
59 | 65 | fn calculate_part2(input: &Vec<Line>) -> u64 { |
60 | | - let mut grid = Grid::<u8>::new_empty(1000, 1000); |
| 66 | + let mut grid = Grid::<u8>::new_empty( |
| 67 | + input.iter().map(|l| l.max_x()).max().unwrap() + 1, |
| 68 | + input.iter().map(|l| l.max_y()).max().unwrap() + 1, |
| 69 | + ); |
61 | 70 | for line in input { |
62 | | - for point in iter(line) { |
63 | | - grid.get_mut(point).map(|e| *e += 1); |
64 | | - } |
| 71 | + write_line_to(&mut grid, line); |
65 | 72 | } |
66 | 73 | grid.entries().filter(|(_, &value)| value >= 2).count() as u64 |
67 | 74 | } |
|
0 commit comments