retroactive, to derust my rust
1use crate::spatial::{
2 Point, adjacent_cardinal_points, all_coords, flood, paths_to_each_point,
3};
4
5pub fn day10_part1(input: &str) -> String {
6 let topomap = parse(input);
7 let digraph = topomap_to_digraph(&topomap);
8 let reachable = all_coords(topomap[0].len(), topomap.len())
9 .filter(|pt| topomap[pt.row][pt.col] == 0)
10 .map(|pt| flood(&digraph, pt))
11 .map(|set| set.iter().filter(|pt| topomap[pt.row][pt.col] == 9).count())
12 .sum::<usize>();
13 reachable.to_string()
14}
15
16pub fn day10_part2(input: &str) -> String {
17 let topomap = parse(input);
18 let digraph = topomap_to_digraph(&topomap);
19 let ratings = all_coords(topomap[0].len(), topomap.len())
20 .filter(|pt| topomap[pt.row][pt.col] == 0)
21 .map(|pt| paths_to_each_point(&digraph, pt))
22 .filter(|grid| {
23 all_coords(topomap[0].len(), topomap.len())
24 .any(|pt| topomap[pt.row][pt.col] == 9 && !grid[pt.row][pt.col].is_empty())
25 })
26 .map(|grid| {
27 all_coords(topomap[0].len(), topomap.len())
28 .filter(|pt| topomap[pt.row][pt.col] == 9)
29 .map(|pt| grid[pt.row][pt.col].len())
30 .sum::<usize>()
31 });
32 ratings.sum::<usize>().to_string()
33}
34
35fn parse(input: &str) -> Vec<Vec<u8>> {
36 input
37 .lines()
38 .map(|line| {
39 line.chars()
40 .map(|c| c.to_digit(10).unwrap_or(11) as u8)
41 .collect()
42 })
43 .collect()
44}
45///adjacency list in graph format
46fn topomap_to_digraph(topomap: &[Vec<u8>]) -> Vec<Vec<Vec<Point>>> {
47 let mut digraph = vec![vec![vec![]; topomap[0].len()]; topomap.len()];
48 for row in 0..topomap.len() {
49 for col in 0..topomap[0].len() {
50 let adj = adjacent_cardinal_points(topomap, Point { row, col });
51 digraph[row][col] = adj
52 .into_iter()
53 .filter(|pt| topomap[pt.row][pt.col] == 1 + topomap[row][col])
54 .collect();
55 }
56 }
57
58 digraph
59}