-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
245 lines (215 loc) · 6.45 KB
/
lib.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
242
243
244
245
use std::fs;
use std::collections::VecDeque;
use std::collections::HashMap;
pub fn part1(input_file: &str) -> usize {
let mut input = parse_input(input_file);
let mut sum = PulseCount::new();
for _ in 0..1000 {
sum.add(&cycle(&mut input));
}
sum.product()
}
pub fn part2(input_file: &str) -> usize {
let mut total = 1;
let input = parse_input(input_file);
let mut rx_input_gate: String = String::from("");
for (label,value) in &input {
if value.output.len() == 1 && value.output[0] == "rx".to_string() {
rx_input_gate = label.clone();
break;
}
}
for gate in input.get(&rx_input_gate).unwrap().input.iter() {
total *= get_cycles_before_high(&mut input.clone(), gate.clone());
}
total
}
fn get_cycles_before_high(input: &mut HashMap<String,Gate>, label: String) -> usize {
let mut num_cycles = 0;
while !input.get(&label).unwrap().get_sent_high() {
cycle(input);
num_cycles += 1;
}
num_cycles
}
fn cycle(h: &mut HashMap<String,Gate>) -> PulseCount {
let mut curr = h.get(&"broadcaster".to_string()).unwrap();
let mut pulses = PulseCount::new();
let output = Gate::new(GateKind::Output);
pulses.inc_low();
let mut queue: VecDeque<(String,String)> = VecDeque::new();
for output in curr.output.iter() {
queue.push_back(("broadcaster".to_string(),output.clone()));
}
while queue.len() > 0 {
// Only immutable references to the hashmap here
let (sender,recipient) = queue.pop_front().unwrap();
curr = h.get(&recipient).unwrap_or_else(|| &output);
let (state,count) = curr.get_updated_state(&*h, &sender);
// Check if either not a state or pulse was low
if curr.get_type() == GateKind::Output {
pulses.add(&count);
continue;
} else if curr.get_type() != GateKind::State || state != curr.get_state() {
for s in curr.output.iter() {
queue.push_back((recipient.clone(),s.clone()));
}
}
if curr.get_type() == GateKind::Nand && state {
if !curr.get_sent_high() {
h.entry(recipient.clone()).and_modify(|s| s.set_sent_high());
}
}
// Actually update hashmap here
h.entry(recipient).and_modify(|s| s.set_state(state));
pulses.add(&count);
}
pulses
}
#[derive(Debug)]
struct PulseCount {
low: usize,
high: usize,
}
impl PulseCount {
fn new() -> Self {
Self{ low: 0, high: 0 }
}
fn inc_high(&mut self) {
self.high += 1;
}
fn inc_low(&mut self) {
self.low += 1;
}
fn add(&mut self, o: &PulseCount) {
self.low += o.low;
self.high += o.high;
}
fn product(&self) -> usize {
self.low*self.high
}
}
#[derive(Copy,Clone,Debug,PartialEq)]
enum GateKind {
Nand,
State,
Broadcast,
Output,
}
#[derive(Clone,Debug)]
struct Gate {
kind: GateKind,
output: Vec<String>,
input: Vec<String>,
state: bool,
sent_high: bool,
}
impl Gate {
fn new(kind: GateKind) -> Self {
Self {kind, output: vec![], input: vec![], state: false, sent_high: false}
}
fn set_state(&mut self, state: bool) {
self.state = state;
}
fn set_sent_high(&mut self) {
self.sent_high = true;
}
fn get_sent_high(&self) -> bool {
self.sent_high
}
fn get_state(&self) -> bool {
self.state
}
fn get_type(&self) -> GateKind {
self.kind
}
fn get_updated_state(&self, h: &HashMap<String,Gate>, sender: &String) -> (bool, PulseCount) {
let mut pulses = PulseCount::new();
let mut state: bool = h.get(sender).unwrap().get_state();
if state {
pulses.inc_high();
} else {
pulses.inc_low();
}
match self.kind {
GateKind::Broadcast => state = true,
GateKind::Output => (),
GateKind::State => {
if state {
// If the pulse is high do nothing
state = self.state;
} else {
// If the pulse is low flip
state = !self.state;
}
},
GateKind::Nand => {
let high = self.input.iter().filter(|s|{
h.get(*s).unwrap().get_state()
}).count();
if high == self.input.len() {
state = false;
} else {
state = true;
}
},
}
(state, pulses)
}
}
fn parse_input(input_file: &str) -> HashMap<String,Gate> {
let input = fs::read_to_string(input_file)
.expect("Unable to open input data");
let mut out: HashMap<String,Gate> = HashMap::new();
// First pass create our gates
for item in input.trim().split("\n") {
let gate;
let (mut item, _) = item.split_once(" -> ").unwrap();
match item.chars().nth(0).unwrap() {
'%' => {
gate = Gate::new(GateKind::State);
item = item.strip_prefix("%").unwrap();
},
'&' => {
gate = Gate::new(GateKind::Nand);
item = item.strip_prefix("&").unwrap();
},
'b' => {
gate = Gate::new(GateKind::Broadcast);
}
_ => unreachable!(),
}
out.insert(String::from(item),gate);
}
// Second pass link our input and outputs
for item in input.trim().split("\n") {
let (mut item, list) = item.split_once(" -> ").unwrap();
match item.chars().nth(0).unwrap() {
'%' => {
item = item.strip_prefix("%").unwrap();
},
'&' => {
item = item.strip_prefix("&").unwrap();
},
'b' => (),
_ => unreachable!(),
}
let list: Vec<&str> = list.split(", ").collect();
let item = String::from(item);
for entry in list {
let entry = String::from(entry);
out.entry(entry.clone()).and_modify(|e| e.input.push(item.clone()));
out.entry(item.clone()).and_modify(|e| e.output.push(entry));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test1() {
assert_eq!(part1("data/test.txt"), 32000000);
assert_eq!(part1("data/test2.txt"), 11687500);
}
}