From aa65136b9296a27379ce1edd53daa2a23390f748 Mon Sep 17 00:00:00 2001 From: Louis Vallat Date: Thu, 9 Jan 2025 09:53:14 +0100 Subject: [PATCH] feat: added day 22 part 1 and 2 Signed-off-by: Louis Vallat --- .gitea/workflows/build_and_run.yml | 2 +- day22/Cargo.toml | 6 +++ day22/src/main.rs | 66 ++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 day22/Cargo.toml create mode 100644 day22/src/main.rs diff --git a/.gitea/workflows/build_and_run.yml b/.gitea/workflows/build_and_run.yml index 5444adb..6a96701 100644 --- a/.gitea/workflows/build_and_run.yml +++ b/.gitea/workflows/build_and_run.yml @@ -11,7 +11,7 @@ jobs: name: Challenge for day strategy: matrix: - day_number: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21] + day_number: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22] runs-on: rust-bookworm steps: - name: Check out repository code diff --git a/day22/Cargo.toml b/day22/Cargo.toml new file mode 100644 index 0000000..07fb531 --- /dev/null +++ b/day22/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "day22" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/day22/src/main.rs b/day22/src/main.rs new file mode 100644 index 0000000..36d30fe --- /dev/null +++ b/day22/src/main.rs @@ -0,0 +1,66 @@ +use std::{env, fs}; + +const ITERATIONS: usize = 2000; + +fn xor_shift(mut secret: i64) -> i64 { + secret ^= secret << 6; + secret &= (1 << 24) - 1; + secret ^= secret >> 5; + secret ^= secret << 11; + secret &= (1 << 24) - 1; + secret +} + +fn read_input(path: &str) -> String { + fs::read_to_string(path).expect("Cannot read file.") +} + +fn parse_input(input: &str) -> Vec { + input + .lines() + .filter(|line| !line.is_empty()) + .map(|line| line.parse().unwrap()) + .collect() +} + +fn compute_market(secrets: &Vec) -> (i64, i64) { + let mut secrets_sum = 0; + let (mut last_monkey, mut cache) = (vec![None; 160000], vec![0; 160000]); + + for (monkey, &secret) in secrets.iter().enumerate() { + let mut secret = secret; + let mut previous_price = 0; + let mut a; + let (mut b, mut c, mut d) = (0, 0, 0); + + for i in 0..ITERATIONS { + secret = xor_shift(secret); + let price = secret % 10; + (a, b, c, d) = (b, c, d, 9 + price - previous_price); + + if i > 2 { + let key = (a * 6859 + b * 361 + c * 19 + d) as usize; + if last_monkey[key].is_none() || last_monkey[key].unwrap() != monkey { + last_monkey[key] = Some(monkey); + cache[key] += price; + } + } + previous_price = price; + } + secrets_sum += secret; + } + + (secrets_sum, *cache.iter().max().unwrap()) +} + +fn main() { + let args: Vec = env::args().collect(); + for arg in args.iter().skip(1) { + let input = read_input(&arg); + let secrets = parse_input(&input); + let (secrets_sum, best_price) = compute_market(&secrets); + println!("[{}]", &arg); + println!("\t[Part 1] => Answer is '{}'.", secrets_sum); + println!("\t[Part 2] => Answer is '{}'.", best_price); + } +}