95 lines
2.3 KiB
Rust
95 lines
2.3 KiB
Rust
use std;
|
|
|
|
fn compute_intcode(p: &mut Vec<usize>) -> Vec<usize> {
|
|
for idx in (0..(p.len())).step_by(4) {
|
|
match p[idx] {
|
|
1 => {
|
|
let left = p[idx + 1];
|
|
let right = p[idx + 2];
|
|
let res = p[idx + 3];
|
|
p[res] = p[left] + p[right];
|
|
}
|
|
2 => {
|
|
let left = p[idx + 1];
|
|
let right = p[idx + 2];
|
|
let res = p[idx + 3];
|
|
p[res] = p[left] * p[right];
|
|
}
|
|
99 => break,
|
|
_ => panic!("Something went wrong!"),
|
|
}
|
|
}
|
|
p.to_vec()
|
|
}
|
|
|
|
pub fn part_one() {
|
|
let mut input: Vec<usize> = std::include_str!("../day2-input.txt")
|
|
.trim()
|
|
.split(",")
|
|
.map(|x| x.parse().unwrap())
|
|
.collect();
|
|
|
|
input[1] = 12;
|
|
input[2] = 2;
|
|
|
|
println!("Intcode [0] is: {}", compute_intcode(&mut input)[0]);
|
|
}
|
|
|
|
pub fn part_two() {
|
|
let mut input: Vec<usize> = std::include_str!("../day2-input.txt")
|
|
.trim()
|
|
.split(",")
|
|
.map(|x| x.parse().unwrap())
|
|
.collect();
|
|
|
|
input[1] = 0;
|
|
input[2] = 0;
|
|
|
|
let lookup_num = 19690720;
|
|
let mut found = false;
|
|
|
|
for i in 0..99 {
|
|
input[1] = i;
|
|
for j in 0..99 {
|
|
input[2] = j;
|
|
let mut input_guess = input.clone();
|
|
let computed = compute_intcode(&mut input_guess);
|
|
|
|
found = computed[0] == lookup_num;
|
|
|
|
if found {
|
|
let (noun, verb) = (computed[1], computed[2]);
|
|
println!(
|
|
"100 * noun({}) + verb({}) = {}",
|
|
noun,
|
|
verb,
|
|
100 * noun + verb
|
|
);
|
|
break;
|
|
}
|
|
}
|
|
if found {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_part_one() {
|
|
assert_eq!(
|
|
compute_intcode(&mut vec!(1, 0, 0, 0, 99)),
|
|
vec!(2, 0, 0, 0, 99)
|
|
);
|
|
assert_eq!(
|
|
compute_intcode(&mut vec!(2, 3, 0, 3, 99)),
|
|
vec!(2, 3, 0, 6, 99)
|
|
);
|
|
assert_eq!(
|
|
compute_intcode(&mut vec!(2, 4, 4, 5, 99, 0)),
|
|
vec!(2, 4, 4, 5, 99, 9801)
|
|
);
|
|
assert_eq!(
|
|
compute_intcode(&mut vec!(1, 1, 1, 4, 99, 5, 6, 0, 99)),
|
|
vec!(30, 1, 1, 4, 2, 5, 6, 0, 99)
|
|
);
|
|
}
|