-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
162 lines (147 loc) · 4.85 KB
/
mod.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
use std::collections::HashMap;
use std::collections::VecDeque;
use petgraph::Directed;
use petgraph::graphmap::GraphMap;
use petgraph_evcxr::draw_graph;
const DEBUG: bool = false;
#[derive(Debug, Clone, PartialEq, Eq)]
enum ModuleType{
Broadcast,
Conjunction(HashMap<String, bool>),
FlipFlop(bool),
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Module {
typ: ModuleType,
name: String,
next: Vec<String>,
}
impl Module {
fn pulse(&mut self, list: &mut VecDeque<(String, String, bool)>, module: &str, input: bool) {
let forward: Option<bool> = match self.typ {
ModuleType::Broadcast => Some(input),
ModuleType::Conjunction(ref mut inputs) => {
let v = inputs.get_mut(module).unwrap();
*v = input;
let mut all_high = true;
for v in inputs.values_mut() {
if !*v {
all_high = false;
}
}
Some(!all_high)
},
ModuleType::FlipFlop(ref mut state) => match input {
// high pulse is ignored and nothing happens
true => None,
// low pulse fips on/off
false => {
*state = !*state;
Some(*state)
}
}
};
if let Some(f) = forward {
for n in self.next.iter() {
if DEBUG {
println!("{} {f} => {n}", self.name);
}
list.push_back((n.clone(), self.name.clone(), f));
}
}
}
}
fn button_press(modules: &mut HashMap<String, Module>) -> (bool, (usize, usize)) {
let mut cnt = (0, 0);
let mut call_list = VecDeque::new();
let mut found = false;
call_list.push_back(("roadcaster".to_owned(), "".to_owned(), false));
while let Some((i, j, k)) = call_list.pop_front() {
if (i == "bh" || i == "dl" || i == "vd" || i == "ns") && !k {
if DEBUG {
println!("{} {} => {}", j, k, i);
}
found = true;
}
match k {
false => cnt.0 += 1,
true => cnt.1 += 1,
}
if let Some(m) = modules.get_mut(&i) {
m.pulse(&mut call_list, &j, k);
}
}
if DEBUG {
println!();
for (k, v) in modules {
println!("{:?} {:?}", k, v);
}
println!();
}
(found, cnt)
}
pub fn solve(input: String) {
let mut input_map: HashMap<String, Vec<String>> = HashMap::new();
let mut modules = HashMap::new();
if DEBUG {
// see visualization.png
let mut graph: GraphMap<&str, &str, Directed> = GraphMap::new();
for line in input.lines() {
let (name_raw, next_str) = line.split_once(" -> ").unwrap();
let next: Vec<_> = next_str.split(", ").collect();
let name = &name_raw[1..];
for i in next {
graph.add_edge(name, i, &name_raw[0..1]);
}
}
draw_graph(&graph);
}
// load modules
for line in input.lines() {
let (name_raw, next_str) = line.split_once(" -> ").unwrap();
let next: Vec<_> = next_str.split(", ").map(|s| s.to_owned()).collect();
let name = name_raw[1..].to_owned();
let module: Module = Module{name: name.clone(), next: next.clone(), typ: match &name_raw[0..1] {
"b" => ModuleType::Broadcast,
"%" => ModuleType::FlipFlop(false),
"&" => ModuleType::Conjunction(HashMap::<String, bool>::new()),
_ => unreachable!(),
}};
for i in next {
input_map.entry(i.clone()).and_modify(|v| v.push(name.clone())).or_insert(vec![name.clone()]);
}
modules.insert(name, module);
}
// update inputs
for (k, v) in &mut modules {
if let ModuleType::Conjunction(ref mut inputs) = v.typ {
for i in input_map[k].iter() {
inputs.insert(i.to_owned(), false);
}
}
}
let mut cnt = (0,0);
let mut vals = [0; 4];
// split up, see visualization.png
for (j, n) in ["ls", "bv", "dc", "br"].iter().enumerate() {
modules.entry("roadcaster".to_owned()).and_modify(|v| v.next = vec![n.to_string()]);
for i in 0..10000 {
let (res, add) = button_press(&mut modules);
if i < 1000 {
cnt.0 += add.0;
cnt.1 += add.1;
}
if res {
// +1 for pulse to zh
vals[j] = i + 1;
if DEBUG {
println!("min {}", i + 1);
}
break;
}
}
}
// we count initial low pulse from broadcaster x4 => 3 times too much
cnt.0 -= 3000;
aoc::print_solution(&[cnt.0 * cnt.1, aoc::lcm(&vals)]);
}