Skip to content

Commit

Permalink
Day 01 Part 01 Solution
Browse files Browse the repository at this point in the history
  • Loading branch information
mattcr11 committed Dec 1, 2024
1 parent 889a62c commit 1584d9e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
6 changes: 6 additions & 0 deletions data/examples/01.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
3 4
4 3
2 5
1 3
3 9
3 3
34 changes: 32 additions & 2 deletions src/bin/01.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,37 @@
advent_of_code::solution!(1);

pub fn part_one(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 and sort
let sorted = (0..pairs[0].len())
.map(|list_index| {
let mut unsorted = pairs
.iter()
.map(|line| line[list_index])
.collect::<Vec<_>>();
unsorted.sort();
unsorted
})
.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<_>>();

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

pub fn part_two(input: &str) -> Option<u32> {
Expand All @@ -15,7 +45,7 @@ mod tests {
#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, None);
assert_eq!(result, Some(11));
}

#[test]
Expand Down

0 comments on commit 1584d9e

Please sign in to comment.