[CLEANUP] Removed duplicate code in Day 10

This commit is contained in:
2022-12-11 20:08:48 +01:00
parent afa80765cf
commit e33875103f

View File

@@ -28,6 +28,22 @@ impl Day10 {
.collect(), .collect(),
} }
} }
fn execute<F>(&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 { impl DaySolver for Day10 {
@@ -35,49 +51,29 @@ impl DaySolver for Day10 {
fn solve_part1(&mut self) -> String { fn solve_part1(&mut self) -> String {
let mut x = 1;
let mut cycle = 1;
let mut interesting_cycle_sum = 0; let mut interesting_cycle_sum = 0;
for instr in &self.instructions { self.execute(|cycle, x| {
if (cycle + 20) % 40 == 0 {
for _ in 0..instr.cycles() { // println!("{} * {} = {}", x, cycle, x * cycle);
if (cycle + 20) % 40 == 0 { interesting_cycle_sum += x * cycle;
// println!("{} * {} = {}", x, cycle, x * cycle);
interesting_cycle_sum += x * cycle;
}
cycle += 1;
} }
});
if let Instruction::Addx(addx) = instr {
x += addx;
}
}
return interesting_cycle_sum.to_string(); return interesting_cycle_sum.to_string();
} }
fn solve_part2(&mut self) -> String { fn solve_part2(&mut self) -> String {
let mut x: i32 = 1; let mut res = String::from("\n");
let mut cycle = 1; self.execute(|cycle, x| {
let mut res: String = String::from("\n"); if x.abs_diff((cycle - 1) % 40) <= 1 {
for instr in &self.instructions { res += "#";
} else {
for _ in 0..instr.cycles() { res += "."
if x.abs_diff((cycle - 1) % 40) <= 1 {
res += "#";
} else {
res += "."
}
if cycle % 40 == 0 {
res += "\n";
}
cycle += 1;
} }
if cycle % 40 == 0 {
if let Instruction::Addx(addx) = instr { res += "\n";
x += addx;
} }
} });
return res; return res;
} }