2019: day07: simplify part2 logic

This commit is contained in:
Antoine Martin 2019-12-09 16:48:16 +01:00
parent 4e1fecf3ee
commit 3ea1ca4ec5

View file

@ -88,18 +88,13 @@ fn part2(input: &str) -> Result<i64> {
} }
intcodes[0].add_input(0); intcodes[0].add_input(0);
let mut signal = None;
let mut num_halted = 0;
loop { loop {
for i in 0..(intcodes.len() - 1) { for i in 0..(intcodes.len() - 1) {
let (first, second) = intcodes.split_at_mut(i + 1); let (first, second) = intcodes.split_at_mut(i + 1);
let intcode = &mut first[i]; let intcode = &mut first[i];
let next = &mut second[0]; let next = &mut second[0];
let halted = intcode.run_and_wait()?; intcode.run_and_wait()?;
if halted {
num_halted += 1;
}
for out in intcode.output.iter() { for out in intcode.output.iter() {
next.add_input(*out); next.add_input(*out);
@ -114,27 +109,19 @@ fn part2(input: &str) -> Result<i64> {
let halted = last.run_and_wait()?; let halted = last.run_and_wait()?;
if halted { if halted {
let out = last match last.get_last_output() {
.output Some(signal) => {
.last() res = std::cmp::max(res, signal);
.copied() break;
.ok_or_else(|| err!("last amplifier halted without output"))?; }
signal = Some(out); None => return Err(err!("last amplifier halted without output")),
};
} else { } else {
for out in last.output.iter() { for out in last.output.iter() {
first.add_input(*out); first.add_input(*out);
} }
last.output.clear(); last.output.clear();
} }
if let Some(signal) = signal {
res = std::cmp::max(res, signal);
break;
}
if num_halted >= 4 {
return Err(err!("all non final amplifiers halted, feedback loop stuck"));
}
} }
} }