Skip to content

Commit a96bc7a

Browse files
committed
don't search multiple times the same value
1 parent 1aa85cc commit a96bc7a

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/aoc2024/day1.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::collections::HashMap;
2+
13
use crate::aoc2024::Aoc2024;
24
use crate::traits::days::Day1;
35
use crate::traits::ParseInput;
@@ -45,9 +47,13 @@ impl Solution<Day1> for Aoc2024 {
4547

4648
fn part2((left, right): &(Vec<u32>, Vec<u32>)) -> u32 {
4749
let mut score = 0;
50+
let mut counts = HashMap::new();
51+
52+
for &l in left {
53+
let count = *counts.entry(l).or_insert_with(|| {
54+
right.iter().filter(|&&r| r == l).count() as u32
55+
});
4856

49-
for l in left {
50-
let count = right.iter().filter(|&r| r == l).count() as u32;
5157
score += l * count;
5258
}
5359

0 commit comments

Comments
 (0)