diff --git a/src/problem8/lib.rs b/src/problem8/lib.rs index 45fed38..d11cc2c 100644 --- a/src/problem8/lib.rs +++ b/src/problem8/lib.rs @@ -1,21 +1,40 @@ use crate::Problem; +use std::collections::HashSet; +#[derive(Clone, Debug)] pub struct Problem8 { - number_list: Vec, + operations: Vec<(Op, OpAnd)>, } +#[derive(Clone, Copy, Debug)] +enum Op { + Nop, + Acc, + Jmp, +} + +#[derive(Clone, Copy, Debug)] +struct OpAnd(i32); + impl Problem8 {} impl Problem for Problem8 { fn new(input: &String) -> Self { Problem8 { - number_list: input + operations: input .split("\n") .filter_map(|s| { let s = s.trim(); if !s.is_empty() { - Some(s.parse::().unwrap()) + let mut v = s.split(" "); + let op = match v.next().unwrap().trim() { + "nop" => {Op::Nop}, + "acc" => {Op::Acc}, + "jmp" => {Op::Jmp}, + _ =>{println!("unsupported operand {}", s); Op::Nop} + }; + Some((op, OpAnd(v.next().unwrap().trim().parse::().unwrap()))) } else { None } @@ -24,11 +43,73 @@ impl Problem for Problem8 { } fn run_part1(&self) { + return; + println!("{:?}", self.operations); + + let mut repeats : HashSet = HashSet::default(); + let mut pc : i32 = 0; + let mut acc : i32 = 0; + while !repeats.contains(&pc) { + repeats.insert(pc); + match self.operations.get(pc as usize).unwrap() { + &(Op::Nop, opand) => { + pc += 1; + }, + &(Op::Acc, opand) => { + acc += opand.0 as i32; + pc += 1; + }, + &(Op::Jmp, opand) => { + pc += opand.0 as i32; + } + } + println!("{:?}, {:?}, {:?}", pc, acc, repeats) + } } fn run_part2(&self) { + println!("{:?}", self.operations); + + for (i, v) in self.operations.iter().enumerate() { + let mut base_ops = self.operations.clone(); + + match v { + &(Op::Nop, opand) => { + base_ops[i] = (Op::Jmp, opand); + }, + &(Op::Acc, opand) => { + + }, + &(Op::Jmp, opand) => { + base_ops[i] = (Op::Nop, opand); + } + } + + let mut repeats : HashSet = HashSet::default(); + let mut pc : i32 = 0; + let mut acc : i32 = 0; + while !repeats.contains(&pc) && pc < self.operations.len() as i32{ + repeats.insert(pc); + match base_ops.get(pc as usize).unwrap() { + &(Op::Nop, opand) => { + pc += 1; + }, + &(Op::Acc, opand) => { + acc += opand.0 as i32; + pc += 1; + }, + &(Op::Jmp, opand) => { + pc += opand.0 as i32; + } + } + //println!("{:?}, {:?}, {:?}", pc, acc, repeats) + } + + println!("{:?}", acc); + println!("pc {:?}, len {:?}, contains {:?}", pc, repeats.contains(&pc), self.operations.len()) + } } }