Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
85 lines (71 loc) · 2.12 KB
/
Copy pathlib.rs
File metadata and controls
85 lines (71 loc) · 2.12 KB
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
use anyhow::Result;
use std::collections::HashMap;
type Graph<'a> = HashMap<&'a str, Vec<&'a str>>;
pub fn parse(input: &str) -> Graph<'_> {
let mut grid: Graph = HashMap::new();
for line in input.lines() {
let parts: Vec<&str> = line.split(": ").collect();
let key = parts[0];
let neighbors: Vec<&str> = parts[1].split_whitespace().collect();
grid.entry(key).or_default().extend(neighbors);
}
grid
}
fn count_paths<'a>(
curr: &'a str,
target: &'a str,
graph: &Graph<'a>,
memo: &mut HashMap<(&'a str, &'a str), u64>,
) -> u64 {
if curr == target {
return 1;
}
let key = (curr, target);
if let Some(&count) = memo.get(&key) {
return count;
}
let mut total = 0;
if let Some(neighbors) = graph.get(curr) {
for &nxt in neighbors {
total += count_paths(nxt, target, graph, memo);
}
}
memo.insert(key, total);
total
}
pub fn part_1(input: &str) -> Result<String> {
let grid = parse(input);
let mut memo = HashMap::new();
let result = count_paths("you", "out", &grid, &mut memo);
Ok(result.to_string())
}
pub fn part_2(input: &str) -> Result<String> {
let grid = parse(input);
let mut memo = HashMap::new();
let p1 = count_paths("svr", "dac", &grid, &mut memo)
* count_paths("dac", "fft", &grid, &mut memo)
* count_paths("fft", "out", &grid, &mut memo);
let p2 = count_paths("svr", "fft", &grid, &mut memo)
* count_paths("fft", "dac", &grid, &mut memo)
* count_paths("dac", "out", &grid, &mut memo);
Ok((p1 + p2).to_string())
}
#[cfg(test)]
mod tests {
use super::*;
fn input() -> String {
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/input.txt")).unwrap()
}
#[test]
fn test_part_1() {
let result = part_1(&input()).unwrap();
println!("Part 1 result: {}", result);
assert!(!result.is_empty());
}
#[test]
fn test_part_2() {
let result = part_2(&input()).unwrap();
println!("Part 2 result: {}", result);
assert!(!result.is_empty());
}
}