diff options
author | j-james | 2022-12-12 03:22:14 +0000 |
---|---|---|
committer | j-james | 2022-12-12 03:22:14 +0000 |
commit | 9d00a16d832f6a864a44ce21261338fac3180539 (patch) | |
tree | 7b4bde430f68d7068a383e82e478c0ab222aa9f9 /2022 | |
parent | a7ba598a54a8883c83cb9ef2b04d653eecd92e28 (diff) |
Day Ten (Rust)
Diffstat (limited to '2022')
-rw-r--r-- | 2022/rust/day10/Cargo.lock | 7 | ||||
-rw-r--r-- | 2022/rust/day10/Cargo.toml | 8 | ||||
-rw-r--r-- | 2022/rust/day10/src/main.rs | 65 |
3 files changed, 80 insertions, 0 deletions
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<Ins> = 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::<i32>().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; +} |