-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday20.rs
241 lines (216 loc) · 7.07 KB
/
day20.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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
use std::collections::{HashMap, VecDeque};
use aoc_lib::{answer::Answer, solution::Solution};
pub struct Day20;
impl Solution for Day20 {
fn part_a(&self, input: &[String]) -> Answer {
let modules = parse(input);
const NUMBER_OF_PRESS: usize = 1000;
let mut result = [0, NUMBER_OF_PRESS - 1];
simulate_button_presses(&modules, |i, _curr, _dest, pulse| {
match pulse {
Pulse::High => result[0] += 1,
Pulse::Low => result[1] += 1,
}
i < NUMBER_OF_PRESS
});
(result[0] * result[1]).into()
}
fn part_b(&self, input: &[String]) -> Answer {
let modules = parse(input);
let ic = important_connections(&modules);
let mut last_cycle = [0_usize; 4];
let mut cycle_len = [0_usize; 4];
simulate_button_presses(&modules, |i, curr, dest, pulse| {
if dest == "nr" && pulse == Pulse::High {
if let Some(j) = ic.iter().position(|s| s == &curr) {
let last = last_cycle[j];
last_cycle[j] = i;
cycle_len[j] = i - last + 1;
if cycle_len.iter().all(|&i| i != 0) {
return false;
}
}
}
true
});
cycle_len.iter().product::<usize>().into()
}
}
fn simulate_button_presses<'a>(
modules: &HashMap<&'a str, Module<'a>>,
mut hook: impl FnMut(usize, &str, &str, Pulse) -> bool,
) {
let mut queue = VecDeque::new();
let mut flip_flop_mem = HashMap::new();
let mut conjuctions_mem = HashMap::new();
for m in modules.values() {
match m.module_type {
ModuleType::FlipFlop => {
flip_flop_mem.insert(m.source, FlipFlopState::Off);
}
ModuleType::Conjuction => {
let mut map = HashMap::new();
for om in modules.values() {
if om.destinations.contains(&m.source) {
map.insert(om.source, Pulse::Low);
}
}
conjuctions_mem.insert(m.source, map);
}
_ => continue,
}
}
for i in 0.. {
queue.clear();
let broadcaster = modules.get("broadcaster").unwrap();
for t in broadcaster.destinations.iter() {
queue.push_back(("broadcaster", *t, Pulse::Low));
}
while let Some((curr, dest, pulse)) = queue.pop_front() {
if !hook(i, curr, dest, pulse) {
return;
}
let Some(module) = modules.get(dest) else {
continue;
};
let pulse_type = match module.module_type {
ModuleType::Normal => continue,
ModuleType::FlipFlop => {
let state = flip_flop_mem.get_mut(dest).unwrap();
match pulse {
Pulse::High => continue,
Pulse::Low => match state {
FlipFlopState::On => {
*state = FlipFlopState::Off;
Pulse::Low
}
FlipFlopState::Off => {
*state = FlipFlopState::On;
Pulse::High
}
},
}
}
ModuleType::Conjuction => {
let module_mem = conjuctions_mem.get_mut(dest).unwrap();
let previous_state = module_mem.get_mut(curr).unwrap();
*previous_state = pulse;
if module_mem.values().all(|&p| p == Pulse::High) {
Pulse::Low
} else {
Pulse::High
}
}
_ => continue,
};
for futur in module.destinations.iter() {
queue.push_back((dest, futur, pulse_type));
}
}
}
}
fn important_connections<'a>(modules: &HashMap<&'a str, Module>) -> Vec<&'a str> {
// the final module 'rx' in my input is targeted by only one conjuction module,
// which gonna send a Low pulse only if all connected modules Last sent pulse was high
// this function find all those 'important' modules;
let connected_to_finals = modules
.iter()
.find(|(_, v)| v.destinations.contains(&"rx"))
.map(|(k, _)| k)
.unwrap();
modules
.iter()
.filter(|(_, v)| v.destinations.contains(connected_to_finals))
.map(|(&k, _)| k)
.collect::<Vec<_>>()
}
fn parse(input: &[String]) -> HashMap<&str, Module> {
let mut modules = HashMap::new();
for line in input {
let (source, dest) = line.split_once("->").unwrap();
let source = source.trim();
let module_type = ModuleType::from(source);
let source = match module_type {
ModuleType::FlipFlop | ModuleType::Conjuction => &source[1..source.len()],
_ => source,
};
let destinations = dest.trim().split(',').map(|d| d.trim()).collect::<Vec<_>>();
modules.insert(
source,
Module {
source,
module_type,
destinations,
},
);
}
modules
}
#[derive(Debug, PartialEq, Copy, Clone)]
enum Pulse {
Low,
High,
}
enum FlipFlopState {
On,
Off,
}
#[derive(Debug, Hash, PartialEq, Eq)]
struct Module<'a> {
source: &'a str,
destinations: Vec<&'a str>,
module_type: ModuleType,
}
#[derive(Debug, PartialEq, Eq, Hash)]
enum ModuleType {
// low is true and high is false
FlipFlop,
Conjuction,
Broadcast,
Normal,
}
impl From<&str> for ModuleType {
fn from(value: &str) -> Self {
match value.chars().nth(0).unwrap() {
'b' => ModuleType::Broadcast,
'%' => ModuleType::FlipFlop,
'&' => ModuleType::Conjuction,
_ => ModuleType::Normal,
}
}
}
#[cfg(test)]
mod test {
use aoc_lib::{self, answer::Answer, input, solution::Solution};
use super::Day20;
#[test]
fn test_a_1() {
let input = input::read_file(&format!(
"{}day_20_a_test_1.txt",
crate::FILES_PREFIX_TEST
))
.unwrap();
let answer = Day20.part_a(&input);
assert_eq!(<i32 as Into<Answer>>::into(32000000), answer);
}
#[test]
fn test_a_2() {
let input = input::read_file(&format!(
"{}day_20_a_test_2.txt",
crate::FILES_PREFIX_TEST
))
.unwrap();
let answer = Day20.part_a(&input);
assert_eq!(<i32 as Into<Answer>>::into(11687500), answer);
}
#[test]
fn test_b() {
let input = input::read_file(&format!(
"{}day_20_b_test.txt",
crate::FILES_PREFIX_TEST
))
.unwrap();
let answer = Day20.part_b(&input);
assert_eq!(<i64 as Into<Answer>>::into(228282646835717), answer);
}
}