[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,23 +28,14 @@ impl Day10 {
.collect(), .collect(),
} }
} }
}
impl DaySolver for Day10 { fn execute<F>(&self, mut cycle_fun: F) where F: FnMut(&i32, &i32) {
let mut x: i32 = 1;
fn solve_part1(&mut self) -> String {
let mut x = 1;
let mut cycle = 1; let mut cycle = 1;
let mut interesting_cycle_sum = 0;
for instr in &self.instructions { for instr in &self.instructions {
for _ in 0..instr.cycles() { for _ in 0..instr.cycles() {
if (cycle + 20) % 40 == 0 { cycle_fun(&cycle, &x);
// println!("{} * {} = {}", x, cycle, x * cycle);
interesting_cycle_sum += x * cycle;
}
cycle += 1; cycle += 1;
} }
@@ -52,17 +43,28 @@ impl DaySolver for Day10 {
x += addx; x += addx;
} }
} }
}
}
impl DaySolver for Day10 {
fn solve_part1(&mut self) -> String {
let mut interesting_cycle_sum = 0;
self.execute(|cycle, x| {
if (cycle + 20) % 40 == 0 {
// println!("{} * {} = {}", x, cycle, x * cycle);
interesting_cycle_sum += x * cycle;
}
});
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");
for instr in &self.instructions {
for _ in 0..instr.cycles() {
if x.abs_diff((cycle - 1) % 40) <= 1 { if x.abs_diff((cycle - 1) % 40) <= 1 {
res += "#"; res += "#";
} else { } else {
@@ -71,13 +73,7 @@ impl DaySolver for Day10 {
if cycle % 40 == 0 { if cycle % 40 == 0 {
res += "\n"; res += "\n";
} }
cycle += 1; });
}
if let Instruction::Addx(addx) = instr {
x += addx;
}
}
return res; return res;
} }