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
|
use std::collections::{HashMap, HashSet};
static DAY: u8 = 10;
fn main() {
let input = advent::read_lines(DAY);
println!("{DAY}a: {}", Map::new(&input).trailhead_score());
println!("{DAY}b: {}", Map::new(&input).distinct_trails());
}
#[derive(Eq, PartialEq, Hash, Copy, Clone)]
struct Position {
x: isize,
y: isize,
}
struct Map {
map: HashMap<Position, u32>,
}
impl Map {
fn new(input: &[String]) -> Map {
let mut map = HashMap::new();
for (y, line) in input.iter().enumerate() {
for (x, c) in line.chars().enumerate() {
let pos = Position { x: x as isize, y: y as isize };
let height = c.to_digit(10).unwrap();
map.insert(pos, height);
}
}
Map { map }
}
fn trailheads(&self) -> Vec<Position> {
self.map.iter()
.filter(|&(_, height)| *height == 0)
.map(|(pos, _)| *pos)
.collect::<Vec<_>>()
}
fn reachable_peaks(&self, pos: &Position) -> HashSet<Position> {
let mut peaks = HashSet::new();
let height = *self.map.get(pos).unwrap();
if height == 9 {
peaks.insert(*pos);
return peaks;
}
for (x, y) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
let neighbor = Position { x: pos.x + x, y: pos.y + y };
if let Some(height_neighbor) = self.map.get(&neighbor) {
if *height_neighbor == height + 1 {
for peak in self.reachable_peaks(&neighbor) {
peaks.insert(peak);
}
}
}
}
peaks
}
fn count_trails(&self, pos: &Position) -> usize {
let height = *self.map.get(pos).unwrap();
if height == 9 {
return 1;
}
let mut trails = 0;
for (x, y) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
let neighbor = Position { x: pos.x + x, y: pos.y + y };
if let Some(height_neighbor) = self.map.get(&neighbor) {
if *height_neighbor == height + 1 {
trails += self.count_trails(&neighbor);
}
}
}
trails
}
fn trailhead_score(&self) -> usize {
self.trailheads().iter()
.map(|trailhead| self.reachable_peaks(trailhead).len())
.sum()
}
fn distinct_trails(&self) -> usize {
self.trailheads().iter()
.map(|trailhead| self.count_trails(trailhead))
.sum()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
let input = [
"89010123",
"78121874",
"87430965",
"96549874",
"45678903",
"32019012",
"01329801",
"10456732",
].iter().map(|&x| String::from(x)).collect::<Vec<_>>();
assert_eq!(Map::new(&input).trailhead_score(), 36);
assert_eq!(Map::new(&input).distinct_trails(), 81);
}
}
|