Skip to content

Commit

Permalink
2024_11
Browse files Browse the repository at this point in the history
  • Loading branch information
hsaikia committed Dec 11, 2024
1 parent 2bf9616 commit 9f0f795
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions src/bin/2024_11/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
use std::collections::HashMap;

use aoc::{common, io};

fn reduce(input: &str) -> String {
let num: usize = io::parse_num(input);
num.to_string()
}

fn evolve(input: &str) -> Vec<String> {
let mut ret: Vec<String> = Vec::new();
if input == "0" {
ret.push("1".to_string());
} else if input.len() % 2 == 0 {
ret.push(reduce(&input[0..input.len() / 2]));
ret.push(reduce(&input[input.len() / 2..]));
} else {
let num: usize = io::parse_num(input);
let new_num = 2024 * num;
ret.push(new_num.to_string());
}
ret
}

fn num_stones(stone: &str, times: usize, cache: &mut HashMap<(String, usize), usize>) -> usize {
if times == 0 {
return 1;
}
if let Some(v) = cache.get(&(stone.to_string(), times)) {
return *v;
}
let mut ans = 0;
let next = evolve(stone);
for ns in next.iter() {
let x = num_stones(ns, times - 1, cache);
ans += x;
}
cache.insert((stone.to_string(), times), ans);
ans
}

fn solve<const ITERATIONS: usize>(input: &str) -> usize {
let mut ans = 0;
let stones: Vec<String> = io::tokenize(input, " ")
.iter()
.map(|s| s.to_string())
.collect();
let mut cache: HashMap<(String, usize), usize> = HashMap::new();
for stone in stones.iter() {
ans += num_stones(stone, ITERATIONS, &mut cache);
}
ans
}

fn main() {
let input = common::get_input();
println!("{input:?}");
common::timed(&input, solve::<25>, true);
common::timed(&input, solve::<75>, false);
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_samples() {
let sample_input = "125 17";
assert_eq!(solve::<25>(sample_input), 55312);
assert_eq!(solve::<75>(sample_input), 65601038650482);
}
}

0 comments on commit 9f0f795

Please sign in to comment.