Day 10. I'm a bit behind. CA trip got in the way

This commit is contained in:
Dustin Swan 2022-12-11 19:49:32 -05:00
parent 7fc1ca6ed4
commit 4b3a9aaa7e
No known key found for this signature in database
GPG key ID: AB49BD6B2B3A6377
5 changed files with 372 additions and 0 deletions

67
day10/src/main.rs Normal file
View file

@ -0,0 +1,67 @@
#[derive(Debug)]
enum Instruction {
Noop,
AddX(i32),
}
fn main() {
let contents = std::fs::read_to_string("data.txt").expect("Failed to read file");
let ops = contents.lines().map(parse).collect::<Vec<Instruction>>();
let strength = run(&ops);
println!("total signal strength {:?}", strength);
}
fn parse(line: &str) -> Instruction {
let parts = line.split(" ").collect::<Vec<&str>>();
match parts[0] {
"noop" => Instruction::Noop,
_ => Instruction::AddX(parts[1].parse().unwrap()),
}
}
fn run(ops: &Vec<Instruction>) -> i32 {
let mut x: i32 = 1;
let mut cycle = 1;
let mut to_add = None;
let mut op_idx = 0;
let mut strength = 0;
while op_idx < ops.len() {
let pixel = cycle % 40;
let diff = (x + 1 - pixel).abs();
if diff.abs() <= 1 {
print!("#");
} else {
print!(" ");
}
match to_add {
None => {
match ops[op_idx] {
Instruction::Noop => (),
Instruction::AddX(v) => {
to_add = Some(v);
}
}
op_idx += 1;
}
Some(v) => {
x += v;
to_add = None;
}
}
if (cycle + 20) % 40 == 0 {
strength += x * cycle;
}
if cycle % 40 == 0 {
println!();
}
cycle += 1;
}
strength
}