Skip to content

Instantly share code, notes, and snippets.

@rondreas
Last active December 2, 2019 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rondreas/3949a440089dbeea25278d1fa84603dd to your computer and use it in GitHub Desktop.
Save rondreas/3949a440089dbeea25278d1fa84603dd to your computer and use it in GitHub Desktop.
Advent of Code 2019, Day 02
use std::env;
use std::fs;
fn run(mut program: Vec<i32>) -> i32 {
for i in (0..program.len()).step_by(4) {
let operation = program[i]; // Operation to use, add/mult/break
let a = program[i+1] as usize;// Index to get first value from
let b = program[i+2] as usize;// Second value
let r = program[i+3] as usize;// Index to store result in
// println!("{} {} {} {}", program[i], program[i+1], program[i+2], program[i+3]);
match operation {
1 => { // Add
program[r] = program[a] + program[b];
}
2 => { // Multiply
program[r] = program[a] * program[b];
}
99 => { // Program is finished,
break;
}
_ => { // Panic on unknown operators, we must have done something wrong then...
panic!("Unknown operator: {}", program[i]);
}
}
};
return program[0];
}
fn main() {
let args: Vec<String> = env::args().collect(); // Get the arguments as a string vector
let filename = &args[1]; // Where the first passed argument should be the path to the file with inputs,
let contents = fs::read_to_string(filename)
.unwrap_or_else(|_| panic!("Failed to read contents of {}", filename));
let numbers = contents.split(','); // Seeing the numbers this time around is a single line, with comma separated values we will split on ','
let mut program = Vec::new();
for number in numbers {
if number.is_empty(){
continue;
}
let opcode = number.parse::<i32>();
let opcode = match opcode {
Ok(result) => result,
Err(_error) => { // Let's just throw away the failed parse
continue;
}
};
program.push(opcode);
}
let program_state: Vec<i32> = program.clone(); // Create an immutable copy of the program state,
// "Restore" the gravity assist program to "1202 program alarm" state
program[1] = 12;
program[2] = 2;
// "Run" the program
let result = run(program);
println!("The result from the program is: {}", result);
let expected_result = 19690720; // The result we are looking for
for x in 0..99 {
for y in 0..99 {
program = program_state.to_vec(); // Restore the program,
program[1] = x; // Set the 'noun'
program[2] = y; // Set the 'verb'
let r = run(program);
if r == expected_result {
println!("The value from correct noun and verb pair was {}", 100 * x + y);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment