From e0ff12f7702911dc498334c0bded3782974ab145 Mon Sep 17 00:00:00 2001 From: Xiretza Date: Sat, 10 Dec 2022 06:29:51 +0100 Subject: [PATCH] 2022 day10/rust: add solution --- 2022/day10/rust/Cargo.toml | 9 +++++ 2022/day10/rust/src/main.rs | 69 +++++++++++++++++++++++++++++++++++++ Cargo.lock | 7 ++++ Cargo.toml | 1 + 4 files changed, 86 insertions(+) create mode 100644 2022/day10/rust/Cargo.toml create mode 100644 2022/day10/rust/src/main.rs diff --git a/2022/day10/rust/Cargo.toml b/2022/day10/rust/Cargo.toml new file mode 100644 index 0000000..6e23673 --- /dev/null +++ b/2022/day10/rust/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "rust_2022_10" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +aoc = { path = "../../../common/rust" } diff --git a/2022/day10/rust/src/main.rs b/2022/day10/rust/src/main.rs new file mode 100644 index 0000000..6c311bb --- /dev/null +++ b/2022/day10/rust/src/main.rs @@ -0,0 +1,69 @@ +#![warn(clippy::pedantic)] + +use std::{ + io::{stdin, Read}, + str::FromStr, +}; + +use aoc::*; + +enum Instruction { + Noop, + Addx(i32), +} + +impl FromStr for Instruction { + type Err = (); + + fn from_str(s: &str) -> Result { + let mut args = s.split_whitespace(); + match args.next().unwrap() { + "noop" => Ok(Self::Noop), + "addx" => { + let i = args.next().unwrap().parse().unwrap(); + Ok(Self::Addx(i)) + } + _ => Err(()), + } + } +} + +fn main() { + let mut data = String::new(); + stdin().read_to_string(&mut data).unwrap(); + + let values = data + .lines() + .map(|l| l.parse().unwrap()) + .flat_map(|i: Instruction| match i { + Instruction::Noop => vec![0], + Instruction::Addx(i) => vec![0, i], + }) + .scan(1, |acc, i| { + *acc += i; + Some(*acc) + }); + let values = [1, 1] + .into_iter() + .chain(values) + .enumerate() + .map(|(i, x)| (i32::try_from(i).unwrap(), x)); + let sum: i32 = values + .clone() + .skip(20) + .step_by(40) + .map(|(i, x)| i * x) + .sum(); + + let crt: Vec<_> = values + .skip(1) + .map(|(i, x)| ((i - 1) % 40 - x).abs() < 2) + .map(|x| if x { '#' } else { '.' }) + .collect(); + let (_, crt) = crt.split_last().unwrap(); + + println!("{:?}", sum); + for line in crt.chunks(40) { + println!("{}", line.iter().collect::()); + } +} diff --git a/Cargo.lock b/Cargo.lock index d8726df..1dfd6d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -531,6 +531,13 @@ dependencies = [ "aoc", ] +[[package]] +name = "rust_2022_10" +version = "0.1.0" +dependencies = [ + "aoc", +] + [[package]] name = "ryu" version = "1.0.11" diff --git a/Cargo.toml b/Cargo.toml index 8c53cdb..0b8679f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,4 +19,5 @@ members = [ "2022/day7/rust", "2022/day8/rust", "2022/day9/rust", + "2022/day10/rust", ]