Last active
December 2, 2019 21:00
-
-
Save hellow554/7a28de253a854a4928c2373beb2beb85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const INPUT: &str = include_str!("../input"); | |
fn parse(s: &str) -> Vec<u32> { | |
s.split(',').map(|x| x.parse().unwrap()).collect() | |
} | |
fn solve_a(memory: &mut [u32]) { | |
const OPS: &[fn(u32, u32) -> u32] = &[ | |
|_, _| panic!("unsupported opcode"), | |
|a, b| a + b, | |
|a, b| a * b, | |
]; | |
let mut ip = 0; | |
loop { | |
match memory[ip] { | |
99 => break, | |
x => { | |
if let [first, second, third] = memory[ip + 1..=ip + 3] { | |
memory[third as usize] = OPS.get(x as usize).expect("unknown opcode")( | |
memory[first as usize], | |
memory[second as usize], | |
) | |
} else { | |
panic!() | |
} | |
} | |
} | |
ip += 4; | |
} | |
} | |
fn solve_b(memory: &[u32], goal: u32) -> u32 { | |
let (_, noun, verb) = (0..=99) | |
.flat_map(|x| (0..=99).map(move |y| (x, y))) | |
.map(|(x, y)| { | |
let mut input = memory.to_vec(); | |
input[1] = x; | |
input[2] = y; | |
solve_a(&mut input); | |
(input[0], x, y) | |
}) | |
.find(|(solution, _, _)| *solution == goal) | |
.unwrap(); | |
100 * noun + verb | |
} | |
fn main() { | |
let input = parse(INPUT); | |
let mut input_a = input.clone(); | |
input_a[1] = 12; | |
input_a[2] = 2; | |
solve_a(&mut input_a); | |
println!("A: {}", input_a[0]); | |
println!("B: {}", solve_b(&input, 19_690_720)); | |
} | |
#[test] | |
fn ta() { | |
let input = "1,9,10,3,2,3,11,0,99,30,40,50"; | |
let mut input = parse(input); | |
solve_a(&mut input); | |
assert_eq!(input, vec![3500, 9, 10, 70, 2, 3, 11, 0, 99, 30, 40, 50]); | |
let mut input = vec![1, 0, 0, 0, 99]; | |
solve_a(&mut input); | |
assert_eq!(input, vec![2, 0, 0, 0, 99]); | |
let mut input = vec![2, 3, 0, 3, 99]; | |
solve_a(&mut input); | |
assert_eq!(input, vec![2, 3, 0, 6, 99]); | |
let mut input = vec![2, 4, 4, 5, 99, 0]; | |
solve_a(&mut input); | |
assert_eq!(input, vec![2, 4, 4, 5, 99, 9801]); | |
let mut input = vec![1, 1, 1, 4, 99, 5, 6, 0, 99]; | |
solve_a(&mut input); | |
assert_eq!(input, vec![30, 1, 1, 4, 2, 5, 6, 0, 99]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment