JonathanGupton

Advent of Code 2022 - Day 4

Dec 4th, 2022
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.51 KB | None | 0 0
  1. use lazy_static::lazy_static;
  2. use regex::Regex;
  3.  
  4. fn full_inclusion_comparison(left: (i32, i32), right: (i32, i32)) -> bool {
  5.     if (left.0 <= right.0 && left.1 >= right.1) || (right.0 <= left.0 && right.1 >= left.1) {
  6.         true
  7.     } else {
  8.         false
  9.     }
  10. }
  11.  
  12. fn partial_inclusion_comparison(left: (i32, i32), right: (i32, i32)) -> bool {
  13.     if (left.0 <= right.1) && (right.0 <= left.1) {
  14.         true
  15.     } else {
  16.         false
  17.     }
  18. }
  19.  
  20. lazy_static! {
  21.     static ref RE: Regex = Regex::new(r"\d+").unwrap();
  22. }
  23.  
  24. fn parse_line(line: &str) -> ((i32, i32), (i32, i32)) {
  25.     let mut found = RE.find_iter(&line);
  26.     let left: (i32, i32) = (
  27.         found.next().unwrap().as_str().parse().unwrap(),
  28.         found.next().unwrap().as_str().parse().unwrap(),
  29.     );
  30.     let right: (i32, i32) = (
  31.         found.next().unwrap().as_str().parse().unwrap(),
  32.         found.next().unwrap().as_str().parse().unwrap(),
  33.     );
  34.     (left, right)
  35. }
  36.  
  37. pub fn part_one(input: &str) -> Option<u32> {
  38.     let mut overlaps: u32 = 0;
  39.     for line in input.lines() {
  40.         let (left, right) = parse_line(line);
  41.         if full_inclusion_comparison(left, right) {
  42.             overlaps += 1;
  43.         }
  44.     }
  45.     Some(overlaps)
  46. }
  47.  
  48. pub fn part_two(input: &str) -> Option<u32> {
  49.     let mut overlaps: u32 = 0;
  50.     for line in input.lines() {
  51.         let (left, right) = parse_line(line);
  52.         if partial_inclusion_comparison(left, right) {
  53.             overlaps += 1;
  54.         }
  55.     }
  56.     Some(overlaps)
  57. }
Advertisement
Add Comment
Please, Sign In to add comment