From 182fd18fc8d591e7067c984993308f911fa36196 Mon Sep 17 00:00:00 2001 From: Tobias Marschner Date: Wed, 21 Feb 2024 22:15:17 +0100 Subject: [PATCH] Solution for 2022/day10-part1 --- 2022/day10-part1/Cargo.toml | 8 ++++++ 2022/day10-part1/src/main.rs | 56 ++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 2022/day10-part1/Cargo.toml create mode 100644 2022/day10-part1/src/main.rs diff --git a/2022/day10-part1/Cargo.toml b/2022/day10-part1/Cargo.toml new file mode 100644 index 0000000..8a6cd11 --- /dev/null +++ b/2022/day10-part1/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "day10-part1" +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/day10-part1/src/main.rs b/2022/day10-part1/src/main.rs new file mode 100644 index 0000000..f0cc8e2 --- /dev/null +++ b/2022/day10-part1/src/main.rs @@ -0,0 +1,56 @@ +fn main() { + // Use command line arguments to specify the input filename. + let args: Vec = std::env::args().collect(); + if args.len() < 2 { + panic!("Usage: ./main \nNo input file provided. Exiting."); + } + + // Next, read the contents of the input file into a string for easier processing. + let input = std::fs::read_to_string(&args[1]).expect("Error opening file"); + // Line-by-line processing is easiest. + let input = input.lines(); + + // --- TASK BEGIN --- + + // Keep track of the current value of X for all the instructions. + // We'll use one massive vector for that purpose. + let mut x_over_time: Vec = Vec::with_capacity(512); + + // Keep track of the actual x as well. + let mut x = 1; + + // Then, process line-by-line. + for line in input { + // Split by space. + let line: Vec<_> = line.split(' ').collect(); + + // Differentiate by instruction + match line[0] { + "noop" => { + // Nothing changes. + x_over_time.push(x); + } + "addx" => { + // Addition is complete *after* two cycles. + // So during those two cycles x has the old value still. + x_over_time.push(x); + x_over_time.push(x); + // Of course, afterwards the value of x is updated. + x += line[1].parse::().unwrap(); + } + _ => () + } + } + + // dbg!(&x_over_time); + + // Afterwards, compute our signal strength result. + let mut signal_strength = 0; + for (i,x) in x_over_time.iter().skip(19).step_by(40).enumerate() { + let cycle: i32 = 20 + (i as i32) * 40; + signal_strength += cycle * x; + } + + println!("Signal strength: {}", signal_strength); +} +