You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.5 KiB
Rust

#[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
}