62 lines
2.1 KiB
Rust
62 lines
2.1 KiB
Rust
use std::collections::HashMap;
|
|
use std::fs;
|
|
|
|
fn main() {
|
|
let content = fs::read_to_string("inputTest.txt").expect("Could not read file");
|
|
let lines: Vec<&str> = content.lines().collect();
|
|
|
|
let mut output_sum = 0;
|
|
let mut output_sum_p2 = 0;
|
|
|
|
// Hashmap with a list of adjacent numbers
|
|
let mut adjacent: HashMap<(usize, usize), Vec<i32>> = HashMap::new();
|
|
|
|
// Create regex automaton outside of the loop for better performance
|
|
let regex = regex::Regex::new(r"\d+").unwrap();
|
|
|
|
for (i, line) in lines.iter().enumerate() {
|
|
for cap in regex.find_iter(line) {
|
|
let match_str = &line[cap.start()..cap.end()];
|
|
let num = match_str.parse::<i32>().unwrap();
|
|
let mut indexes = vec![(i, cap.start().saturating_sub(1)), (i, cap.end())];
|
|
|
|
for k in cap.start().saturating_sub(1)..=cap.end() {
|
|
indexes.push((i.saturating_sub(1), k));
|
|
indexes.push((i + 1, k));
|
|
}
|
|
|
|
for (index1, index2) in indexes {
|
|
if let Some(line) = lines.get(index1) {
|
|
if index2 < lines[index1].len() {
|
|
if let Some(character) = line.chars().nth(index2) {
|
|
if character != '.' {
|
|
output_sum += num;
|
|
|
|
// Part 2
|
|
// Append the number to the adjacency list
|
|
// If no element is found in the hashmap, create it first
|
|
if let Some(adj) = adjacent.get_mut(&(index1, index2)) {
|
|
adj.push(num);
|
|
} else {
|
|
adjacent.insert((index1, index2), vec![num]);
|
|
}
|
|
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
for val in adjacent.values() {
|
|
if val.len() == 2 {
|
|
output_sum_p2 += val[0] * val[1];
|
|
}
|
|
}
|
|
|
|
println!("{}", output_sum);
|
|
println!("{}", output_sum_p2);
|
|
}
|