Skip to content

Commit

Permalink
Merge pull request #87 from ephemient/rs/day11
Browse files Browse the repository at this point in the history
Shorter add-or-insert code pattern
  • Loading branch information
ephemient authored Dec 11, 2024
2 parents 039c7ce + 6704e84 commit d5f3881
Showing 1 changed file with 6 additions and 15 deletions.
21 changes: 6 additions & 15 deletions rs/src/day11.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,34 +13,25 @@ fn solve(data: &str, n: usize) -> Result<u64, ParseIntError> {
Ok((0..n)
.fold(
{
let mut counts = BTreeMap::new();
let mut counts = BTreeMap::<u64, u64>::new();
for word in data.split_ascii_whitespace() {
counts
.entry(word.parse::<u64>()?)
.and_modify(|e| *e += 1)
.or_insert(1u64);
*counts.entry(word.parse()?).or_default() += 1;
}
counts
},
|counts, _| {
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;
}
}
}
Expand Down

0 comments on commit d5f3881

Please sign in to comment.