From: Greg Burri Date: Wed, 11 Dec 2024 19:10:57 +0000 (+0100) Subject: Optimize a bit day 11: reduce to 1.9 ms X-Git-Url: https://git.euphorik.ch/?a=commitdiff_plain;h=d252dc64c44942cc2ac3e5785458c64ef1437383;p=advent_of_code_2024.git Optimize a bit day 11: reduce to 1.9 ms --- diff --git a/src/day07.rs b/src/day07.rs index 0ed8919..05d23e1 100644 --- a/src/day07.rs +++ b/src/day07.rs @@ -70,7 +70,7 @@ pub fn sum_valid_equations_with_concat(equations: &[Equation]) -> i64 { return true; } - let p = 10i64.pow(utils::nb_of_digits(last)); + let p = 10i64.pow(utils::nb_of_digits_i64(last)); if sub % p == 0 { if is_valid(sub / p, &operands[0..l - 1]) { return true; diff --git a/src/day11.rs b/src/day11.rs index 5567a16..c3e3bd1 100644 --- a/src/day11.rs +++ b/src/day11.rs @@ -18,24 +18,20 @@ fn add_or_set(map: &mut Stones, k: u64, n: u64) { pub fn blink(mut stones: Stones, i: u32) -> Stones { for _ in 0..i { - let mut next_stones = Stones::default(); - for (stone, n) in stones { + for (stone, n) in stones.drain().collect::>() { if stone == 0 { - add_or_set(&mut next_stones, 1, n); + add_or_set(&mut stones, 1, n); } else { - let nb_digits = utils::nb_of_digits(stone); + let nb_digits = utils::nb_of_digits_u64(stone); if nb_digits % 2 == 0 { let base = 10u64.pow(nb_digits / 2); - let left = stone / base; - let right = stone - left * base; - add_or_set(&mut next_stones, left, n); - add_or_set(&mut next_stones, right, n); + add_or_set(&mut stones, stone / base, n); + add_or_set(&mut stones, stone % base, n); } else { - add_or_set(&mut next_stones, stone * 2024, n); + add_or_set(&mut stones, stone * 2024, n); } } } - stones = next_stones; } stones } diff --git a/src/utils.rs b/src/utils.rs index a2a1d8d..d9ed680 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,6 +1,4 @@ -use std::{cmp, fmt::Debug, str::FromStr}; - -use num; +use std::{fmt::Debug, str::FromStr}; pub fn split_to_vec(str: &str, pat: &str) -> Vec where @@ -10,15 +8,10 @@ where str.split(pat).map(|v| v.parse::().unwrap()).collect() } -pub fn nb_of_digits(mut v: T) -> u32 -where - T: cmp::PartialOrd + std::ops::DivAssign + num::FromPrimitive + Copy, -{ - let ten = T::from_u32(10).unwrap(); - let mut n = 1; - while v >= ten { - v /= ten; - n += 1; - } - n +pub fn nb_of_digits_u64(v: u64) -> u32 { + v.ilog10() + 1 +} + +pub fn nb_of_digits_i64(v: i64) -> u32 { + v.ilog10() + 1 }