aboutsummaryrefslogtreecommitdiff
path: root/2022/rust/day10/src
diff options
context:
space:
mode:
authorj-james2022-12-12 03:22:14 +0000
committerj-james2022-12-12 03:22:14 +0000
commit9d00a16d832f6a864a44ce21261338fac3180539 (patch)
tree7b4bde430f68d7068a383e82e478c0ab222aa9f9 /2022/rust/day10/src
parenta7ba598a54a8883c83cb9ef2b04d653eecd92e28 (diff)
Day Ten (Rust)
Diffstat (limited to '2022/rust/day10/src')
-rw-r--r--2022/rust/day10/src/main.rs65
1 files changed, 65 insertions, 0 deletions
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;
+}