Skip to content

Commit

Permalink
Day 01 Part 02 Solution
Browse files Browse the repository at this point in the history
  • Loading branch information
mattcr11 committed Dec 1, 2024
1 parent 1584d9e commit 9b4d5fb
Showing 1 changed file with 45 additions and 7 deletions.
52 changes: 45 additions & 7 deletions src/bin/01.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,56 @@ pub fn part_one(input: &str) -> Option<u32> {
.collect::<Vec<_>>();

// compute pair-wise distances
let distances = (0..pairs.len()).map(|line_index| {
(0..sorted.len()).map(|list_index| {
sorted[list_index][line_index]
}).reduce(|acc, e| acc.abs_diff(e)).unwrap()
}).collect::<Vec<_>>();
let distances = (0..pairs.len())
.map(|line_index| {
(0..sorted.len())
.map(|list_index| sorted[list_index][line_index])
.reduce(|acc, e| acc.abs_diff(e))
.unwrap()
})
.collect::<Vec<_>>();

// sum the distances
Some(distances.iter().sum())
}

pub fn part_two(input: &str) -> Option<u32> {
None
// convert string into vector of vectors of numbers in the same configuration
let pairs = input
.lines()
.map(|line| {
line.split(" ")
.map(|item| item.parse::<u32>().unwrap())
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();

// split the lists into individual vectors
let lists = (0..pairs[0].len())
.map(|list_index| {
pairs
.iter()
.map(|line| line[list_index])
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();

// build counts of items in second list
let mut second_set_counts = std::collections::HashMap::new();
lists[1].iter().for_each(|item| {
second_set_counts
.entry(item)
.and_modify(|e| *e += 1)
.or_insert(1);
});

// multiply items in first list by counts from second list and sum up
let similarity = lists[0]
.iter()
.map(|item| item * second_set_counts.get(item).unwrap_or(&0))
.sum();

Some(similarity)
}

#[cfg(test)]
Expand All @@ -51,6 +89,6 @@ mod tests {
#[test]
fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, None);
assert_eq!(result, Some(31));
}
}

0 comments on commit 9b4d5fb

Please sign in to comment.