[TASK] Solved Day 10

This commit is contained in:
2022-12-11 16:17:45 +01:00
parent 563cddce78
commit afa80765cf
4 changed files with 388 additions and 0 deletions

100
src/day10.rs Normal file
View File

@@ -0,0 +1,100 @@
use crate::day_solver::DaySolver;
use super::util;
pub struct Day10 {
instructions: Vec<Instruction>
}
impl Day10 {
pub fn create() -> Self {
// let lines = util::read_file("input/day10_example.txt");
let lines = util::read_file("input/day10.txt");
// Put the input into the day struct
return Day10 {
instructions: lines.iter()
.map(|s| {
if s == "noop" {
Instruction::Noop
} else if s.starts_with("addx") {
Instruction::Addx(s.split_whitespace().last().unwrap().parse::<i32>().unwrap())
} else {
panic!("Unknown instruction {}", s)
}
})
.collect(),
}
}
}
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;
}
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;
}
if let Instruction::Addx(addx) = instr {
x += addx;
}
}
return res;
}
}
#[derive(Debug, Clone)]
enum Instruction {
Noop,
Addx(i32)
}
impl Instruction {
fn cycles(&self) -> u8 {
match self {
Self::Addx(_) => 2,
_ => 1
}
}
}

View File

@@ -8,6 +8,7 @@ use crate::day6::Day6;
use crate::day7::Day7;
use crate::day8::Day8;
use crate::day9::Day9;
use crate::day10::Day10;
use crate::day_solver::DaySolver;
mod util;
@@ -21,6 +22,7 @@ mod day6;
mod day7;
mod day8;
mod day9;
mod day10;
const MAX_DAY: u8 = 9;
const DEFAULT_BENCHMARK_AMOUNT: u32 = 100;
@@ -95,6 +97,7 @@ fn build_day_solver(day: u8) -> Option<Box<dyn DaySolver>> {
7 => Some(Box::new(Day7::create())),
8 => Some(Box::new(Day8::create())),
9 => Some(Box::new(Day9::create())),
10 => Some(Box::new(Day10::create())),
_ => None
}
}