diff --git a/.gitea/workflows/build_and_run.yml b/.gitea/workflows/build_and_run.yml index 2f2b049..db09ccd 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] + day_number: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] runs-on: rust-bookworm steps: - name: Check out repository code diff --git a/day11/Cargo.toml b/day11/Cargo.toml new file mode 100644 index 0000000..d3a547b --- /dev/null +++ b/day11/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "day11" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/day11/src/main.rs b/day11/src/main.rs new file mode 100644 index 0000000..e42d8e3 --- /dev/null +++ b/day11/src/main.rs @@ -0,0 +1,58 @@ +use std::{env, fs}; +use std::collections::HashMap; + +fn read_input(path: &str) -> String { + fs::read_to_string(path).expect("Cannot read file.") +} + +fn parse_input(input: &str) -> Vec { + input.split_whitespace().map(|x| x.parse().unwrap()).collect() +} + + +fn compute_stone(value: usize, remaining_blinks: usize, cache: &mut HashMap<(usize, usize), usize>) -> usize { + if cache.contains_key(&(value, remaining_blinks)) { + return *cache.get(&(value, remaining_blinks)).unwrap(); + } + + if remaining_blinks == 0 { + return 1; + } + + let result; + if value == 0 { + result = compute_stone(1, remaining_blinks - 1, cache); + } else { + let digit = value.to_string(); + if digit.len() % 2 == 0 { + let split = digit.split_at(digit.len() / 2); + result = compute_stone(split.0.parse().unwrap(), remaining_blinks - 1, cache) + + compute_stone(split.1.parse().unwrap(), remaining_blinks - 1, cache); + } else { + result = compute_stone(value * 2024, remaining_blinks - 1, cache); + } + }; + + cache.insert((value, remaining_blinks), result); + result +} + +fn part_1(stones: &Vec) -> usize { + stones.iter().map(|stone| compute_stone(*stone, 25, &mut HashMap::new())).sum() +} + +fn part_2(stones: &Vec) -> usize { + stones.iter().map(|stone| compute_stone(*stone, 75, &mut HashMap::new())).sum() +} + + +fn main() { + let args: Vec = env::args().collect(); + for arg in args.iter().skip(1) { + let input = read_input(&arg); + let stones = parse_input(&input); + println!("[{}]", &arg); + println!("\t[Part 1] => Answer is '{}'.", part_1(&stones)); + println!("\t[Part 2] => Answer is '{}'.", part_2(&stones)); + } +}