Skip to content

Commit d381406

Browse files
Solve Day 1 Part 2
1 parent a27089b commit d381406

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

src/bin/01.rs

+25-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
advent_of_code::solution!(1);
22

3+
use std::collections::HashMap;
4+
35
pub fn part_one(input: &str) -> Option<u32> {
46
// read input into two lists
57
let (mut a, mut b): (Vec<u32>, Vec<u32>) = input
@@ -25,7 +27,28 @@ pub fn part_one(input: &str) -> Option<u32> {
2527
}
2628

2729
pub fn part_two(input: &str) -> Option<u32> {
28-
None
30+
// read input into two lists
31+
let (a, b): (Vec<u32>, Vec<u32>) = input
32+
.lines()
33+
.filter_map(|line| {
34+
let mut parts = line.split_whitespace();
35+
let first = parts.next()?.parse::<u32>().ok()?;
36+
let second = parts.next()?.parse::<u32>().ok()?;
37+
Some((first, second))
38+
})
39+
.unzip();
40+
41+
let b_freq = b.into_iter().fold(HashMap::new(), |mut map, val| {
42+
*map.entry(val).or_insert(0) += 1;
43+
map
44+
});
45+
46+
let similarity_score: u32 = a
47+
.iter()
48+
.map(|x| x * b_freq.get(x).unwrap_or(&0))
49+
.sum();
50+
51+
Some(similarity_score)
2952
}
3053

3154
#[cfg(test)]
@@ -41,6 +64,6 @@ mod tests {
4164
#[test]
4265
fn test_part_two() {
4366
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
44-
assert_eq!(result, None);
67+
assert_eq!(result, Some(31));
4568
}
4669
}

0 commit comments

Comments
 (0)