-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday01.rs
More file actions
84 lines (67 loc) · 1.89 KB
/
day01.rs
File metadata and controls
84 lines (67 loc) · 1.89 KB
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
use std::{collections::HashMap, iter::zip};
fn build_lists(input: &str) -> (Vec<i32>, Vec<i32>) {
let mut left: Vec<i32> = Vec::new();
let mut right: Vec<i32> = Vec::new();
for line in input.lines() {
let trimmed_line = line.trim();
if trimmed_line.is_empty() {
continue;
}
let (l, r) = trimmed_line.split_once(" ").expect("Could not split line.");
left.push(l.trim().parse().expect("Could not parse left side."));
right.push(r.trim().parse().expect("Could not parse right side."));
}
(left, right)
}
fn count(list: Vec<i32>) -> HashMap<i32, i32> {
let mut counts: HashMap<i32, i32> = HashMap::new();
for item in list {
*counts.entry(item).or_insert(0) += 1;
}
counts
}
pub fn task01(input: &str) -> String {
let (mut left, mut right) = build_lists(input);
left.sort();
right.sort();
let mut result = 0;
for (l, r) in zip(left.iter(), right.iter()) {
result += (l - r).abs();
}
result.to_string()
}
pub fn task02(input: &str) -> String {
let (left, right) = build_lists(input);
let counts = count(right);
let mut result = 0;
for item in left.iter() {
let entry = *counts.get(item).unwrap_or(&0);
result += *item * entry;
}
result.to_string()
}
#[cfg(test)]
mod tests {
use super::super::fs_utils::{read_example, read_input};
use super::*;
#[test]
fn test_task01() {
let input = read_example(1, 1);
assert_eq!(task01(&input), "11");
}
#[test]
fn test_task02() {
let input = read_example(1, 1);
assert_eq!(task02(&input), "31");
}
#[test]
fn run_task01() {
let input = read_input(1);
assert_eq!(task01(&input), "3574690");
}
#[test]
fn run_task02() {
let input = read_input(1);
assert_eq!(task02(&input), "22565391");
}
}