-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathday_06.rs
131 lines (108 loc) Β· 2.78 KB
/
day_06.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
use std::collections::HashSet;
use aoc_lib::{direction::cardinal::Direction, matrix::Grid};
use common::{solution, Answer};
use nd_vec::Vec2;
use rayon::iter::{ParallelBridge, ParallelIterator};
solution!("Guard Gallivant", 6);
fn part_a(input: &str) -> Answer {
Map::new(input).visited().len().into()
}
fn part_b(input: &str) -> Answer {
let map = Map::new(input);
map.visited()
.into_iter()
.par_bridge()
.map(|x| map.loops(x) as usize)
.sum::<usize>()
.into()
}
#[derive(Debug, PartialEq, Eq)]
enum Tile {
Obstacle,
Start,
None,
}
struct Map {
map: Grid<Tile>,
start: Vec2<usize>,
}
impl Map {
fn new(input: &str) -> Self {
let map = Grid::parse(input, |x| match x {
'#' => Tile::Obstacle,
'^' => Tile::Start,
_ => Tile::None,
});
let start = map.find(Tile::Start).unwrap();
Self { map, start }
}
fn visited(&self) -> HashSet<Vec2<usize>> {
let mut seen = HashSet::new();
let mut pos = self.start;
let mut direction = Direction::Up;
loop {
seen.insert(pos);
let Some(mut next) = direction.try_advance(pos) else {
break;
};
let Some(tile) = self.map.get(next) else {
break;
};
if *tile == Tile::Obstacle {
direction = direction.turn_right();
next = match direction.try_advance(pos) {
Some(x) => x,
None => break,
}
}
pos = next;
}
seen
}
fn loops(&self, obstacle: Vec2<usize>) -> bool {
let mut seen = HashSet::new();
let mut pos = self.start;
let mut direction = Direction::Up;
loop {
let Some(tile) = self.map.get(pos) else {
break;
};
if obstacle == pos || *tile == Tile::Obstacle {
pos = direction.opposite().advance(pos);
direction = direction.turn_right();
}
if !seen.insert((pos, direction)) {
return true;
}
pos = match direction.try_advance(pos) {
Some(x) => x,
None => break,
};
}
false
}
}
#[cfg(test)]
mod test {
use indoc::indoc;
const CASE: &str = indoc! {"
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
"};
#[test]
fn part_a() {
assert_eq!(super::part_a(CASE), 41.into());
}
#[test]
fn part_b() {
assert_eq!(super::part_b(CASE), 6.into());
}
}