From 6704e843926c3c87736f65b7d75bb53af14950ac Mon Sep 17 00:00:00 2001 From: Daniel Lin Date: Wed, 11 Dec 2024 03:22:04 -0500 Subject: [PATCH] Shorter add-or-insert code pattern --- rs/src/day11.rs | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/rs/src/day11.rs b/rs/src/day11.rs index 962f7c1..ae75269 100644 --- a/rs/src/day11.rs +++ b/rs/src/day11.rs @@ -13,12 +13,9 @@ fn solve(data: &str, n: usize) -> Result { Ok((0..n) .fold( { - let mut counts = BTreeMap::new(); + let mut counts = BTreeMap::::new(); for word in data.split_ascii_whitespace() { - counts - .entry(word.parse::()?) - .and_modify(|e| *e += 1) - .or_insert(1u64); + *counts.entry(word.parse()?).or_default() += 1; } counts }, @@ -26,21 +23,15 @@ fn solve(data: &str, n: usize) -> Result { let mut next = BTreeMap::new(); for (num, count) in counts { if num == 0 { - next.entry(1).and_modify(|e| *e += count).or_insert(count); + *next.entry(1).or_default() += count; } else { let length = num.ilog10() + 1; if length % 2 == 0 { let divisor = 10u64.pow(length / 2); - next.entry(num / divisor) - .and_modify(|e| *e += count) - .or_insert(count); - next.entry(num % divisor) - .and_modify(|e| *e += count) - .or_insert(count); + *next.entry(num / divisor).or_default() += count; + *next.entry(num % divisor).or_default() += count; } else { - next.entry(2024 * num) - .and_modify(|e| *e += count) - .or_insert(count); + *next.entry(2024 * num).or_default() += count; } } }