summaryrefslogtreecommitdiffstats
path: root/2022/day4/part1
diff options
context:
space:
mode:
authorYigit Sever2022-12-06 14:47:43 +0300
committerYigit Sever2022-12-06 14:47:43 +0300
commit244d3dfa233371db0adcff329283bb1ce9bba9f5 (patch)
treed6ec2d6682a45c823bf0ee9f921f861f3cefe118 /2022/day4/part1
parentef7e8df2825480f34c1034015a8221c09f6ebdf6 (diff)
downloadaoc-244d3dfa233371db0adcff329283bb1ce9bba9f5.tar.gz
aoc-244d3dfa233371db0adcff329283bb1ce9bba9f5.tar.bz2
aoc-244d3dfa233371db0adcff329283bb1ce9bba9f5.zip
2022, day4: done
Diffstat (limited to '2022/day4/part1')
-rw-r--r--2022/day4/part1/Cargo.toml9
-rw-r--r--2022/day4/part1/src/main.rs50
2 files changed, 59 insertions, 0 deletions
diff --git a/2022/day4/part1/Cargo.toml b/2022/day4/part1/Cargo.toml
new file mode 100644
index 0000000..f14fe90
--- /dev/null
+++ b/2022/day4/part1/Cargo.toml
@@ -0,0 +1,9 @@
1[package]
2name = "part1"
3version = "0.1.0"
4edition = "2021"
5
6# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7
8[dependencies]
9itertools = "0.10.5"
diff --git a/2022/day4/part1/src/main.rs b/2022/day4/part1/src/main.rs
new file mode 100644
index 0000000..a4b7e38
--- /dev/null
+++ b/2022/day4/part1/src/main.rs
@@ -0,0 +1,50 @@
1use itertools::Itertools;
2
3#[derive(Debug)]
4struct Elf {
5 start: usize,
6 end: usize,
7}
8
9#[derive(Debug)]
10struct Pair(Elf, Elf);
11
12impl 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
24impl 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
34impl Pair {
35 fn contains(&self) -> bool {
36 return (self.0.start <= self.1.start && self.0.end >= self.1.end)
37 || (self.0.start >= self.1.start && self.0.end <= self.1.end);
38 }
39}
40
41fn main() {
42 let sum: usize = include_str!("../../example")
43 .lines()
44 .map(|l| Pair::new(l))
45 .map(|p| p.contains())
46 .filter(|r| *r)
47 .count();
48
49 println!("{}", sum);
50}