aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--2022/rust/day10/Cargo.lock7
-rw-r--r--2022/rust/day10/Cargo.toml8
-rw-r--r--2022/rust/day10/src/main.rs65
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, &register);
+ tick(&mut clock);
+ compare(&clock, &register, &mut sum);
+ if let Ins::Addr(x) = ins {
+ render(&clock, &register);
+ tick(&mut clock);
+ write(&mut register, x);
+ compare(&clock, &register, &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;
+}