diff --git a/src/day10.rs b/src/day10.rs index 8e3de99..d0e2c22 100644 --- a/src/day10.rs +++ b/src/day10.rs @@ -28,6 +28,22 @@ impl Day10 { .collect(), } } + + fn execute(&self, mut cycle_fun: F) where F: FnMut(&i32, &i32) { + let mut x: i32 = 1; + let mut cycle = 1; + for instr in &self.instructions { + + for _ in 0..instr.cycles() { + cycle_fun(&cycle, &x); + cycle += 1; + } + + if let Instruction::Addx(addx) = instr { + x += addx; + } + } + } } impl DaySolver for Day10 { @@ -35,49 +51,29 @@ impl DaySolver for Day10 { fn solve_part1(&mut self) -> String { - let mut x = 1; - let mut cycle = 1; let mut interesting_cycle_sum = 0; - for instr in &self.instructions { - - for _ in 0..instr.cycles() { - if (cycle + 20) % 40 == 0 { - // println!("{} * {} = {}", x, cycle, x * cycle); - interesting_cycle_sum += x * cycle; - } - cycle += 1; + self.execute(|cycle, x| { + if (cycle + 20) % 40 == 0 { + // println!("{} * {} = {}", x, cycle, x * cycle); + interesting_cycle_sum += x * cycle; } - - if let Instruction::Addx(addx) = instr { - x += addx; - } - } + }); return interesting_cycle_sum.to_string(); } fn solve_part2(&mut self) -> String { - let mut x: i32 = 1; - let mut cycle = 1; - let mut res: String = String::from("\n"); - for instr in &self.instructions { - - for _ in 0..instr.cycles() { - if x.abs_diff((cycle - 1) % 40) <= 1 { - res += "#"; - } else { - res += "." - } - if cycle % 40 == 0 { - res += "\n"; - } - cycle += 1; + let mut res = String::from("\n"); + self.execute(|cycle, x| { + if x.abs_diff((cycle - 1) % 40) <= 1 { + res += "#"; + } else { + res += "." } - - if let Instruction::Addx(addx) = instr { - x += addx; + if cycle % 40 == 0 { + res += "\n"; } - } + }); return res; }