generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
dd6e0a2
commit 8bbf655
Showing
2 changed files
with
69 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
use std::collections::HashMap; | ||
|
||
advent_of_code::solution!(1); | ||
|
||
pub fn part_one(input: &str) -> Option<u32> { | ||
let (mut l, mut r): (Vec<i32>, Vec<i32>) = input | ||
.lines() | ||
.map(|l| { | ||
let mut nums = l.split_whitespace().map(|n| n.parse::<i32>().unwrap()); | ||
(nums.next().unwrap(), nums.next().unwrap()) | ||
}) | ||
.unzip(); | ||
|
||
l.sort(); | ||
r.sort(); | ||
|
||
let sum: i32 = l.iter().zip(r.iter()).map(|(l, r)| (l - r).abs()).sum(); | ||
Some(sum as u32) | ||
} | ||
|
||
pub fn part_two(input: &str) -> Option<u32> { | ||
let (l, r): (Vec<i32>, Vec<i32>) = input | ||
.lines() | ||
.map(|l| { | ||
let mut nums = l.split_whitespace().map(|n| n.parse::<i32>().unwrap()); | ||
(nums.next().unwrap(), nums.next().unwrap()) | ||
}) | ||
.unzip(); | ||
|
||
let mut r_count: HashMap<i32, usize> = HashMap::new(); | ||
|
||
for n in r.iter() { | ||
*r_count.entry(*n).or_insert(0) += 1; | ||
} | ||
|
||
let score: i32 = l | ||
.iter() | ||
.map(|&n| { | ||
let count = *r_count.get(&n).unwrap_or(&0); | ||
let score = n * count as i32; | ||
score | ||
}) | ||
.sum(); | ||
|
||
Some(score as u32) | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn test_part_one() { | ||
let result = part_one(&advent_of_code::template::read_file("examples", DAY)); | ||
assert_eq!(result, Some(11)); | ||
} | ||
|
||
#[test] | ||
fn test_part_two() { | ||
let result = part_two(&advent_of_code::template::read_file("examples", DAY)); | ||
assert_eq!(result, Some(31)); | ||
} | ||
} |