summaryrefslogtreecommitdiffstats
path: root/day1/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'day1/src/main.rs')
-rw-r--r--day1/src/main.rs106
1 files changed, 106 insertions, 0 deletions
diff --git a/day1/src/main.rs b/day1/src/main.rs
new file mode 100644
index 0000000..fd78563
--- /dev/null
+++ b/day1/src/main.rs
@@ -0,0 +1,106 @@
1struct Day1 {}
2
3impl Day1 {
4 fn part_n(&self, input: BufReader<Box<dyn Read>>) -> (Vec<u32>, Vec<u32>) {
5 let mut a: Vec<u32> = vec![];
6 let mut b: Vec<u32> = vec![];
7
8 for line in self.read_lines(input) {
9 let mut s = line.split(' ');
10
11 loop {
12 let ia = s.next().unwrap();
13
14 let num = match ia.parse::<u32>() {
15 Ok(num) => num,
16 Err(_) => continue,
17 };
18
19 a.push(num);
20 break;
21 }
22
23 loop {
24 let ib = s.next_back().unwrap();
25
26 let num = match ib.parse::<u32>() {
27 Ok(num) => num,
28 Err(_) => continue,
29 };
30
31 b.push(num);
32 break;
33 }
34 }
35
36 (a, b)
37 }
38}
39
40impl Day for Day1 {
41 fn example_input(&self) -> &'static str {
42 r#"
43 3 4
44 4 3
45 2 5
46 1 3
47 3 9
48 3 3
49 "#.trim()
50 }
51
52 fn example_result_part_1(&self) -> &'static str {
53 "11"
54 }
55
56 fn example_result_part_2(&self) -> &'static str {
57 "31"
58 }
59
60 fn part_1(&self, input: BufReader<Box<dyn Read>>) -> String {
61 let (mut a, mut b) = self.part_n(input);
62
63 a.sort();
64 b.sort();
65
66 let mut distances: Vec<u32> = vec![];
67 for (ia, ib) in a.iter().zip(b) {
68 if *ia > ib {
69 distances.push(ia - ib);
70 } else {
71 distances.push(ib - ia);
72 }
73 }
74
75 format!("{}", (distances.iter().sum::<u32>()))
76 }
77
78 fn part_2(&self, input: BufReader<Box<dyn Read>>) -> String {
79 let (a, b) = self.part_n(input);
80
81 let mut scores: Vec<u32> = vec![];
82 for item in a {
83 let count = b.iter().filter(|&&i| i == item).count();
84 scores.push(item * count as u32);
85 }
86
87 format!("{}", (scores.iter().sum::<u32>()))
88 }
89}
90
91use aoc;
92use std::io::{BufReader, Read};
93use aoc::Day;
94
95fn main() {
96 aoc::main(&Day1 {});
97}
98
99#[cfg(test)]
100mod tests {
101 use super::*;
102 #[test]
103 fn test_day1() {
104 aoc::test_day(&Day1 {});
105 }
106}