Advertisement
EvEnSGRIANch

Untitled

Dec 3rd, 2023
1,306
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.66 KB | None | 0 0
  1. use regex::Regex;
  2. use std::collections::HashSet;
  3. use std::io::{self, BufRead};
  4.  
  5. fn main() {
  6.     let re_tokens = Regex::new(r"([0-9]+)|([^0-9.]+)").unwrap();
  7.     let stdin = io::stdin();
  8.     let mut res: i32 = 0;
  9.     let mut number_positions: Vec<(i32, (i32, i32))> = Vec::new();
  10.     let mut position_parts: HashSet<(i32, i32)> = HashSet::new();
  11.  
  12.     for (line_no, line) in stdin.lock().lines().enumerate() {
  13.         let haystack = &line.unwrap();
  14.         let tokens = re_tokens.find_iter(haystack);
  15.         for token in tokens {
  16.             // println!("{}", token.as_str());
  17.             match token.as_str().parse::<i32>() {
  18.                 Ok(ok) => {
  19.                     number_positions.push((
  20.                         ok,
  21.                         (
  22.                             line_no.try_into().unwrap(),
  23.                             token.start().try_into().unwrap(),
  24.                         ),
  25.                     ));
  26.                 }
  27.                 Err(_e) => {
  28.                     let _ = position_parts.insert((
  29.                         line_no.try_into().unwrap(),
  30.                         token.start().try_into().unwrap(),
  31.                     ));
  32.                 }
  33.             }
  34.         }
  35.     }
  36.     for (value, (row, col)) in number_positions {
  37.         let len: i32 = value.to_string().len().try_into().unwrap();
  38.         for i in col - 1..col + len + 1 {
  39.             if position_parts.contains(&(row - 1, i))
  40.                 || position_parts.contains(&(row, i))
  41.                 || position_parts.contains(&(row + 1, i))
  42.             {
  43.                 res += value;
  44.                 break;
  45.             }
  46.         }
  47.     }
  48.     print!("{}", res);
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement