[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(),
}
}
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 {
@@ -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;
}