From 9d00a16d832f6a864a44ce21261338fac3180539 Mon Sep 17 00:00:00 2001 From: j-james Date: Sun, 11 Dec 2022 19:22:14 -0800 Subject: Day Ten (Rust) --- 2022/rust/day10/Cargo.lock | 7 +++++ 2022/rust/day10/Cargo.toml | 8 ++++++ 2022/rust/day10/src/main.rs | 65 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 2022/rust/day10/Cargo.lock create mode 100644 2022/rust/day10/Cargo.toml create mode 100644 2022/rust/day10/src/main.rs (limited to '2022/rust') diff --git a/2022/rust/day10/Cargo.lock b/2022/rust/day10/Cargo.lock new file mode 100644 index 0000000..5f8ea61 --- /dev/null +++ b/2022/rust/day10/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "day10" +version = "0.1.0" diff --git a/2022/rust/day10/Cargo.toml b/2022/rust/day10/Cargo.toml new file mode 100644 index 0000000..40d2066 --- /dev/null +++ b/2022/rust/day10/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "day10" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/2022/rust/day10/src/main.rs b/2022/rust/day10/src/main.rs new file mode 100644 index 0000000..89849ea --- /dev/null +++ b/2022/rust/day10/src/main.rs @@ -0,0 +1,65 @@ +use std::env; +use std::fs; + +#[derive(Eq, PartialEq)] +enum Ins { + Noop, + Addr(i32) +} + +fn main() { + let args = env::args().nth(1).expect("missing input"); + let input = fs::read_to_string(args).unwrap(); + + let instructions: Vec = input.trim().split("\n") + .map(|x| { + if x == "noop" { + return Ins::Noop; + } else { + let val = x.split_whitespace().nth(1).unwrap(); + return Ins::Addr(val.parse::().unwrap()); + } + }).collect(); + + let mut sum = 0; + let mut clock = 1; + let mut register = 1; + + for ins in instructions { + render(&clock, ®ister); + tick(&mut clock); + compare(&clock, ®ister, &mut sum); + if let Ins::Addr(x) = ins { + render(&clock, ®ister); + tick(&mut clock); + write(&mut register, x); + compare(&clock, ®ister, &mut sum); + } + } + println!("{}", sum); +} + +fn render(clock: &i32, register: &i32) { + if i32::abs(register - ((clock-1) % 40)) < 2 { + print!("#"); + } else { + print!("."); + } + if clock % 40 == 0 { + print!("\n"); + } +} + +fn tick(clock: &mut i32) { + *clock += 1; +} + +fn compare(clock: &i32, register: &i32, sum: &mut i32) { + if clock % 40 == 20 { + *sum += *register * *clock; + } +} + +fn write(register: &mut i32, value: i32) { + *register += value; +} -- cgit v1.2.3-70-g09d2