[TASK] Solved Day 8

This commit is contained in:
2020-12-08 11:25:08 +01:00
parent 3046716c5f
commit 48bea13e9d
4 changed files with 750 additions and 0 deletions

96
src/day8.rs Normal file
View File

@@ -0,0 +1,96 @@
use super::util;
pub fn solve() {
let lines = util::read_file("input/day8.txt");
let program = lines.iter().map(|s| Instruction::parse(s)).collect::<Vec<_>>();
let part1 = execute(&program);
println!("Day 8 Part 1: {}", part1.unwrap_err().0);
for i in 0..program.len() {
let ins = &program[i];
if ins.op == Operation::ACC {
// No flip needed
continue;
}
let mut new_program = program.to_vec();
if ins.op == Operation::JMP {
new_program[i] = Instruction {
op: Operation::NOP,
arg: ins.arg
}
} else if ins.op == Operation::NOP {
new_program[i] = Instruction {
op: Operation::JMP,
arg: ins.arg
}
}
let res = execute(&new_program);
if res.is_ok() {
let part2 = res.unwrap();
println!("Day 8 Part 2: {}", part2);
break;
}
}
}
fn execute(instructions: &[Instruction]) -> Result<i32, (i32, String)> {
let mut acc = 0;
let mut p = 0;
let mut visited = vec![false; instructions.len()];
loop {
if p == instructions.len() {
return Result::Ok(acc);
} else if p > instructions.len() {
return Result::Err((acc, String::from("Out of bounds")));
} else if visited[p] {
return Result::Err((acc, String::from("Infinite loop")));
}
let ins = &instructions[p];
visited[p] = true;
match ins.op {
Operation::JMP => p = ((p as i32) + ins.arg) as usize,
Operation::ACC => acc += ins.arg,
_ => ()/* Nothing to do here */,
}
if ins.op != Operation::JMP {
p += 1;
}
}
}
#[derive(Debug, Clone)]
struct Instruction {
op: Operation,
arg: i32
}
impl Instruction {
fn parse(line: &str) -> Instruction {
let split = line.split_ascii_whitespace().collect::<Vec<_>>();
let op;
match &split.get(0).unwrap()[..] {
"acc" => op = Operation::ACC,
"jmp" => op = Operation::JMP,
"nop" => op = Operation::NOP,
_ => panic!("Unknown instruction: {}", split.get(0).unwrap())
}
return Instruction {
op,
arg: split.get(1).map(|x| x.parse::<i32>().unwrap()).unwrap_or(0)
}
}
}
#[derive(Debug, PartialEq, Clone)]
enum Operation {
NOP, ACC, JMP
}

View File

@@ -9,6 +9,7 @@ mod day4;
mod day5;
mod day6;
mod day7;
mod day8;
fn main() {
@@ -26,6 +27,7 @@ fn main() {
5 => day5::solve(),
6 => day6::solve(),
7 => day7::solve(),
8 => day8::solve(),
_ => println!("This day is not yet implemented")
}
} else {
@@ -37,6 +39,7 @@ fn main() {
day5::solve();
day6::solve();
day7::solve();
day8::solve();
}
println!("Execution took {} μs", now.elapsed().as_micros());