-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday01.rs
95 lines (79 loc) · 2.11 KB
/
day01.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use itertools::Itertools;
use crate::solution::{AocError, Solution};
pub struct Day01;
fn parse(input: &str) -> Result<(Vec<u32>, Vec<u32>), AocError> {
let result: Vec<(u32, u32)> = input
.trim()
.lines()
.map(|line| {
let (left_input, right_input) = line
.trim()
.split_once(" ")
.ok_or(AocError::parse(input, "Invalid input"))?;
let left = left_input
.parse::<u32>()
.map_err(|err| AocError::parse(left_input, err))?;
let right = right_input
.parse::<u32>()
.map_err(|err| AocError::parse(right_input, err))?;
Ok((left, right))
})
.try_collect()?;
Ok(result.into_iter().unzip())
}
impl Solution for Day01 {
type Part1 = u32;
type Part2 = u32;
fn default_input(&self) -> &'static str {
include_str!("../../../inputs/2024/day01.txt")
}
fn part_1(&self, input: &str) -> Result<u32, AocError> {
let (mut left, mut right) = parse(input)?;
left.sort();
right.sort();
Ok(left
.into_iter()
.zip(right)
.map(|(l, r)| l.abs_diff(r))
.sum())
}
fn part_2(&self, input: &str) -> Result<u32, AocError> {
let (left, right) = parse(input)?;
Ok(left
.iter()
.map(|l| (right.iter().filter(|r| *r == l).count() as u32) * l)
.sum())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_solves_part1_example() {
assert_eq!(
Day01.part_1(
"3 4\n\
4 3\n\
2 5\n\
1 3\n\
3 9\n\
3 3"
),
Ok(11)
);
}
#[test]
fn it_solves_part2_example() {
assert_eq!(
Day01.part_2(
"3 4\n\
4 3\n\
2 5\n\
1 3\n\
3 9\n\
3 3"
),
Ok(31)
);
}
}