github.com/mnlphlp/aoc22@v0.0.0-20230330151331-c1dc4bff1b9b/aoc22_rust/src/day04.rs (about) 1 use crate::types::Task; 2 3 #[derive(Default, Copy, Clone)] 4 struct SecRange { 5 start: i32, 6 end: i32, 7 } 8 9 type Pair = [SecRange; 2]; 10 11 fn fully_overlap(p: &Pair) -> bool { 12 p[0].start >= p[1].start && p[0].end <= p[1].end 13 || p[1].start >= p[0].start && p[1].end <= p[0].end 14 } 15 fn overlap(p: &Pair) -> bool { 16 p[0].start >= p[1].start && p[0].start <= p[1].end 17 || p[1].start >= p[0].start && p[1].start <= p[0].end 18 } 19 20 fn parse_input(input: &str) -> Vec<Pair> { 21 let lines = input.lines(); 22 let mut pairs: Vec<Pair> = Vec::new(); 23 for line in lines { 24 let ranges = line.split(","); 25 let mut pair = [SecRange::default(); 2]; 26 for (j, r) in ranges.enumerate() { 27 let ints: Vec<i32> = r.split("-").map(|e| e.parse::<i32>().unwrap()).collect(); 28 pair[j] = SecRange { 29 start: ints[0], 30 end: ints[1], 31 }; 32 } 33 pairs.push(pair); 34 } 35 return pairs; 36 } 37 38 pub fn solve(input: &str, _test: bool, task: Task) -> (String, String) { 39 let pairs = parse_input(input); 40 let (mut res1, mut res2) = ("".to_string(), "".to_string()); 41 42 if !matches!(task, Task::Two) { 43 let count = &pairs.iter().filter(|p| fully_overlap(p)).count(); 44 res1 = count.to_string(); 45 } 46 if !matches!(task, Task::One) { 47 let mut count = 0; 48 for p in pairs { 49 if overlap(&p) { 50 count += 1; 51 } 52 } 53 res2 = count.to_string(); 54 } 55 return (res1, res2); 56 }