-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday01.rs
65 lines (54 loc) · 1.4 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
use crate::solutions::Solution;
pub struct Day01;
impl Solution for Day01 {
fn part_one(&self, input: &str) -> String {
let (mut left, mut right) = self.parse(input);
left.sort_unstable();
right.sort_unstable();
left.iter()
.zip(&right)
.map(|(a, b)| (a - b).abs())
.sum::<i32>()
.to_string()
}
fn part_two(&self, input: &str) -> String {
let (left, right) = self.parse(input);
left.iter()
.map(|l| right.iter().filter(|r| *r == l).count() as i32 * l)
.sum::<i32>()
.to_string()
}
}
impl Day01 {
fn parse(&self, input: &str) -> (Vec<i32>, Vec<i32>) {
input
.lines()
.map(|line| {
let mut split = line.split_terminator(" ");
(
split.next().unwrap().parse::<i32>().unwrap(),
split.next().unwrap().parse::<i32>().unwrap(),
)
})
.unzip()
}
}
#[cfg(test)]
mod tests {
use crate::solutions::year2024::day01::Day01;
use crate::solutions::Solution;
const EXAMPLE: &str = r#"3 4
4 3
2 5
1 3
3 9
3 3"#;
#[test]
fn part_one_example_test() {
assert_eq!("11", Day01.part_one(EXAMPLE));
}
#[test]
fn part_two_example_test() {
assert_eq!("31", Day01.part_two(EXAMPLE));
}
}