diff options
Diffstat (limited to '2022/day4/part2')
-rw-r--r-- | 2022/day4/part2/Cargo.toml | 9 | ||||
-rw-r--r-- | 2022/day4/part2/src/main.rs | 49 |
2 files changed, 58 insertions, 0 deletions
diff --git a/2022/day4/part2/Cargo.toml b/2022/day4/part2/Cargo.toml new file mode 100644 index 0000000..69fa504 --- /dev/null +++ b/2022/day4/part2/Cargo.toml | |||
@@ -0,0 +1,9 @@ | |||
1 | [package] | ||
2 | name = "part2" | ||
3 | version = "0.1.0" | ||
4 | edition = "2021" | ||
5 | |||
6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | ||
7 | |||
8 | [dependencies] | ||
9 | itertools = "0.10.5" | ||
diff --git a/2022/day4/part2/src/main.rs b/2022/day4/part2/src/main.rs new file mode 100644 index 0000000..d7f378a --- /dev/null +++ b/2022/day4/part2/src/main.rs | |||
@@ -0,0 +1,49 @@ | |||
1 | use itertools::Itertools; | ||
2 | |||
3 | #[derive(Debug)] | ||
4 | struct Elf { | ||
5 | start: usize, | ||
6 | end: usize, | ||
7 | } | ||
8 | |||
9 | #[derive(Debug)] | ||
10 | struct Pair(Elf, Elf); | ||
11 | |||
12 | impl Elf { | ||
13 | pub fn new(range: &str) -> Self { | ||
14 | if let Some((start, end)) = range.to_string().split("-").collect_tuple() { | ||
15 | let start: usize = start.parse().unwrap(); | ||
16 | let end: usize = end.parse().unwrap(); | ||
17 | Self { start, end } | ||
18 | } else { | ||
19 | panic!("Expected two elements"); | ||
20 | } | ||
21 | } | ||
22 | } | ||
23 | |||
24 | impl Pair { | ||
25 | pub fn new(line: &str) -> Self { | ||
26 | if let Some((first, second)) = line.to_string().split(",").collect_tuple() { | ||
27 | Pair(Elf::new(first), Elf::new(second)) | ||
28 | } else { | ||
29 | panic!("Expected two elements"); | ||
30 | } | ||
31 | } | ||
32 | } | ||
33 | |||
34 | impl Pair { | ||
35 | fn overlaps(&self) -> bool { | ||
36 | !(self.0.end < self.1.start || self.1.end < self.0.start) | ||
37 | } | ||
38 | } | ||
39 | |||
40 | fn main() { | ||
41 | let sum: usize = include_str!("../../input") | ||
42 | .lines() | ||
43 | .map(|l| Pair::new(l)) | ||
44 | .map(|p| p.overlaps()) | ||
45 | .filter(|r| *r) | ||
46 | .count(); | ||
47 | |||
48 | println!("{}", sum); | ||
49 | } | ||