-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathd11.rs
More file actions
96 lines (75 loc) · 2.44 KB
/
d11.rs
File metadata and controls
96 lines (75 loc) · 2.44 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
86
87
88
89
90
91
92
93
94
95
96
use std::collections::HashMap;
use crate::Day;
pub struct Day11 {}
impl Day for Day11 {
fn year(&self) -> u16 {
2025
}
fn day(&self) -> u8 {
11
}
fn part_one(&self) -> String {
let input = self.read_default_input();
let devices = parse_input(&input);
fn lookup(devices: &HashMap<&str, Vec<&str>>, from: &str) -> usize {
let mut total = 0;
for output in devices
.get(from)
.expect("'from' should be in devices registry")
{
if *output == "out" {
total += 1;
} else {
total += lookup(devices, output)
}
}
total
}
lookup(&devices, "you").to_string()
}
fn part_two(&self) -> String {
let input = self.read_default_input();
let devices = parse_input(&input);
let mut cache: HashMap<(&str, bool, bool), usize> = HashMap::new();
fn lookup<'device>(
devices: &HashMap<&'device str, Vec<&'device str>>,
cache: &mut HashMap<(&'device str, bool, bool), usize>,
from: &'device str,
dac: bool,
fft: bool,
) -> usize {
if let Some(a) = cache.get(&(from, dac, fft)) {
return *a;
}
let dac = dac || from == "dac";
let fft = fft || from == "fft";
let mut total = 0;
for output in devices
.get(from)
.expect("'from' should be in devices registry")
{
if *output == "out" {
if dac && fft {
total += 1;
}
} else {
total += lookup(devices, cache, output, dac, fft);
}
}
cache.insert((from, dac, fft), total);
total
}
lookup(&devices, &mut cache, "svr", false, false).to_string()
}
}
fn parse_input(input: &str) -> HashMap<&str, Vec<&str>> {
let mut devices: HashMap<&str, Vec<&str>> = HashMap::new();
for line in input.lines() {
let [device, output, ..] = line.split(':').collect::<Vec<_>>()[..] else {
panic!("invalid formatted line");
};
let output_devices = output.trim().split(' ').collect::<Vec<_>>();
devices.insert(device, output_devices);
}
devices
}