More intcode refactoring

This commit is contained in:
kageru 2019-12-09 13:25:36 +01:00
parent 56dbed3418
commit 69892c52f4
3 changed files with 41 additions and 31 deletions

View File

@ -2,6 +2,6 @@ use intcode::*;
pub fn main() {
let input = read_input();
println!("Part 1: {}", find_max(0..5, &input));
println!("Part 2: {}", find_max(5..10, &input));
println!("Part 1: {}", find_max(0..5, &input).unwrap());
println!("Part 2: {}", find_max(5..10, &input).unwrap());
}

View File

@ -1,4 +1,5 @@
use itertools::Itertools;
use std::convert::TryFrom;
use std::io::{self, BufRead};
use std::ops::Range;
@ -156,30 +157,37 @@ fn execute(op: Operation, input: &mut Vec<i64>, pos: &mut i64) -> Option<i64> {
}
}
pub fn find_max(range: Range<i64>, input: &Vec<i64>) -> i64 {
range
.permutations(5)
.scan(0, |&mut mut acc, amps| {
let mut machines: Vec<_> = amps
.into_iter()
.map(|amp| Machine {
tape: input.clone(),
pos: 0,
params: vec![amp],
})
.collect();
for state in (0..5).cycle() {
let mut machine = machines.get_mut(state).unwrap();
machine.params.insert(0, acc);
match execute_machine(&mut machine) {
Err(output) => acc = output,
Ok(_) => break,
}
}
Some(acc)
pub fn run_for_input(input: &Vec<i64>, acc: &mut i64, amps: Vec<i64>) -> i64 {
let mut machines: Vec<_> = amps
.into_iter()
.map(|amp| Machine {
tape: input.clone(),
pos: 0,
params: vec![amp],
})
.collect();
for state in (0..machines.len()).cycle() {
let mut machine = machines.get_mut(state).unwrap();
machine.params.insert(0, *acc);
match execute_machine(&mut machine) {
Err(output) => *acc = output,
Ok(_) => break,
}
}
*acc
}
pub fn find_max(range: Range<i64>, input: &Vec<i64>) -> Option<i64> {
usize::try_from(range.end - range.start)
.ok()
.and_then(|len| {
range
.permutations(len)
.scan(0, |&mut mut acc, amps| {
Some(run_for_input(input, &mut acc, amps))
})
.max()
})
.max()
.unwrap()
}
fn execute_machine(machine: &mut Machine) -> Result<i64, i64> {

View File

@ -12,21 +12,23 @@ fn test_find_max() {
0..5,
&parse_test_input("3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0")
),
43210
Some(43210)
);
assert_eq!(
find_max(
0..5,
&parse_test_input("3,23,3,24,1002,24,10,24,1002,23,-1,23,101,5,23,23,1,24,23,23,4,23,99,0,0")
&parse_test_input(
"3,23,3,24,1002,24,10,24,1002,23,-1,23,101,5,23,23,1,24,23,23,4,23,99,0,0"
)
),
54321
Some(54321)
);
assert_eq!(
find_max(
0..5,
&parse_test_input("3,31,3,32,1002,32,10,32,1001,31,-2,31,1007,31,0,33,1002,33,7,33,1,33,31,31,1,32,31,31,4,31,99,0,0,0")
),
65210
Some(65210)
);
}
@ -37,13 +39,13 @@ fn test_find_max_with_loops() {
5..10,
&parse_test_input("3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5")
),
139629729
Some(139629729)
);
assert_eq!(
find_max(
5..10,
&parse_test_input("3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54,-5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4,53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10")
),
18216
Some(18216)
);
}