generated from fspoettel/advent-of-code-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
01.rs
71 lines (61 loc) · 1.74 KB
/
01.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::collections::HashMap;
advent_of_code::solution!(1);
pub fn part_one(input: &str) -> Option<u32> {
let mut left = vec![];
let mut right = vec![];
for line in input.lines() {
let (left_int, right_int): (u32, u32) = line
.split_once(" ")
.map(|(a, b)| (a.parse().unwrap(), b.parse().unwrap()))
.unwrap();
left.push(left_int);
right.push(right_int);
}
left.sort_unstable();
right.sort_unstable();
let mut diff = 0;
for idx in 0..left.len() {
let l_el = left.get(idx).unwrap();
let r_el = right.get(idx).unwrap();
if l_el > r_el {
diff += l_el - r_el;
} else {
diff += r_el - l_el;
}
}
Some(diff)
}
pub fn part_two(input: &str) -> Option<u32> {
let mut left = vec![];
let mut right = HashMap::new();
for line in input.lines() {
let (left_int, right_int): (u32, u32) = line
.split_once(" ")
.map(|(a, b)| (a.parse().unwrap(), b.parse().unwrap()))
.unwrap();
left.push(left_int);
*right.entry(right_int).or_insert(0) += 1;
}
left.sort_unstable();
let mut diff = 0;
for idx in 0..left.len() {
let l_el = left.get(idx).unwrap();
let r_el = right.get(l_el).unwrap_or(&0);
diff += l_el * r_el;
}
Some(diff)
}
#[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));
}
}