Advertisement
Ihmemies

day 03

Dec 3rd, 2023 (edited)
833
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.86 KB | Source Code | 0 0
  1. use regex::Regex;
  2. use std::fs;
  3. use std::time::Instant;
  4. use lazy_static::lazy_static;
  5.  
  6. lazy_static! {
  7.     static ref RE_ID: regex::Regex = Regex::new(r"\d{1,3}").unwrap();
  8.     static ref RE_SYMBOL: regex::Regex = Regex::new(r"[*]").unwrap();
  9. }
  10.  
  11. fn main() {
  12.     let start = Instant::now();
  13.  
  14.     let input = fs::read_to_string("input/03puzzle.txt").unwrap();
  15.     let data: Vec<&str> = input.lines().collect();
  16.     process(&data);
  17.    
  18.     let duration = start.elapsed();
  19.     println!("Time elapsed in main() is: {:?}", duration);
  20. }
  21.  
  22. // find gears and check if they have neighbouring numbers
  23. fn process(data: &[&str]) {    
  24.     let mut sum:i64 = 0;
  25.     for (row, row_str) in data.iter().enumerate() {
  26.         for gear in RE_SYMBOL.find_iter(row_str) {
  27.             sum += check_neighbours(data, &row, &gear.start());            
  28.         }
  29.     }  
  30.     println!("{}", sum); // 84900879
  31. }
  32.  
  33. /**
  34.  *   0  1  2  3  4  5  6  7
  35.  *   8  9 10  * 12 13 14 15
  36.  *  16 17 18 19 20 21 22 23
  37.  */
  38. fn check_neighbours(data: &[&str], row: &usize, col: &usize) -> i64 {
  39.     let start = col.saturating_sub(3);
  40.     let end = start + 7;
  41.  
  42.     let mut neighbours:String = String::new();    
  43.     let mut n1: i64 = 0;
  44.     let mut n2: i64 = 0;
  45.  
  46.     // iterate through rows -1, 0, 1
  47.     for i in 0..3 {
  48.         neighbours += &data[row + i -1][start..end];
  49.         neighbours.push('|');
  50.     }
  51.  
  52.     // check if any numbers are next to the gear in the flattened view
  53.     for num in RE_ID.find_iter(&neighbours) {  
  54.         if (num.start()..num.end())
  55.             .any(|index| [2,3,4,10,12,18,19,20].contains(&index))
  56.         {
  57.             let num_value = num.as_str().parse::<i64>().unwrap_or(-1);
  58.             match (n1, n2) {
  59.                 (0, _) => n1 = num_value,
  60.                 (_, 0) => n2 = num_value,
  61.                 _ => (),
  62.             }
  63.         }
  64.     }
  65.  
  66.     n1*n2
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement