-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday1.rs
58 lines (51 loc) · 1.19 KB
/
day1.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
use itertools::Itertools;
fn parse(data: &str) -> (Vec<i32>, Vec<i32>) {
data.lines()
.filter_map(|line| {
let mut iter = line.split_ascii_whitespace();
let first: i32 = iter.next()?.parse().ok()?;
let second: i32 = iter.next()?.parse().ok()?;
Some((first, second))
})
.unzip()
}
pub fn part1(data: &str) -> i32 {
let (mut first, mut second) = parse(data);
first.sort();
second.sort();
first
.into_iter()
.zip(second.iter())
.map(|(x, y)| (x - y).abs())
.sum()
}
pub fn part2(data: &str) -> i32 {
let (first, second) = parse(data);
let second = second.into_iter().counts();
first
.into_iter()
.map(|x| x * *second.get(&x).unwrap_or(&0) as i32)
.sum()
}
#[cfg(test)]
mod tests {
use super::*;
use indoc::indoc;
use pretty_assertions::assert_eq;
static EXAMPLE: &str = indoc! {"
3 4
4 3
2 5
1 3
3 9
3 3
"};
#[test]
fn part1_examples() {
assert_eq!(11, part1(EXAMPLE));
}
#[test]
fn part2_examples() {
assert_eq!(31, part2(EXAMPLE));
}
}