56 lines
1.5 KiB
Rust
56 lines
1.5 KiB
Rust
use std::collections::HashSet;
|
|
use std::error::Error;
|
|
use std::fs::File;
|
|
use std::io::{self, BufRead};
|
|
use std::vec::Vec;
|
|
|
|
enum Instruction {
|
|
Nop(i32),
|
|
Acc(i32),
|
|
Jmp(i32),
|
|
}
|
|
|
|
fn line_to_instruction(line: String) -> Instruction {
|
|
let mut parts = line.split(" ");
|
|
let opcode = parts.nth(0).unwrap();
|
|
let arg: i32 = parts.nth(0).unwrap().parse().unwrap();
|
|
|
|
match opcode {
|
|
"nop" => Instruction::Nop(arg),
|
|
"acc" => Instruction::Acc(arg),
|
|
"jmp" => Instruction::Jmp(arg),
|
|
_ => panic!("Unsupported Instruction: {}", opcode),
|
|
}
|
|
}
|
|
|
|
fn main() -> Result<(), Box<dyn Error>> {
|
|
let file = File::open("inputs/day8.txt")?;
|
|
let lines = io::BufReader::new(file).lines().map(|l| l.unwrap());
|
|
|
|
let programm: Vec<Instruction> = lines.map(line_to_instruction).collect();
|
|
|
|
let mut pc = 0usize;
|
|
let mut visted: HashSet<usize> = HashSet::new();
|
|
let mut acc = 0i32;
|
|
|
|
while !visted.contains(&pc) {
|
|
visted.insert(pc);
|
|
match programm.get(pc) {
|
|
Some(Instruction::Nop(_)) => pc += 1,
|
|
Some(Instruction::Acc(arg)) => {
|
|
pc += 1;
|
|
acc += arg
|
|
}
|
|
Some(Instruction::Jmp(arg)) => {
|
|
pc = (pc as i32 + arg) as usize;
|
|
}
|
|
None => panic!("PC {} is beyond the programm", pc),
|
|
}
|
|
println!("PC: {}, Acc: {}", pc, acc);
|
|
}
|
|
|
|
println!("Final PC: {}, Final Acc: {}", pc, acc);
|
|
|
|
Ok(())
|
|
}
|