This commit is contained in:
2024-12-03 23:31:21 +01:00
parent fb4cf8e8c0
commit 928218226b
7 changed files with 98 additions and 0 deletions

31
day-01-rust/src/task2.rs Normal file
View File

@@ -0,0 +1,31 @@
use std::collections::HashMap;
use std::str::FromStr;
pub fn run(input: &str) {
let mut first = Vec::<i64>::new();
let mut second = Vec::<i64>::new();
for line in input.split('\n') {
if let Some((first_part, second_part)) = line.split_once(" ") {
match i64::from_str(first_part) {
Ok(n) => first.push(n),
Err(err) => {
eprintln!("Failed to parse first number from {}: {}", first_part, err);
}
}
match i64::from_str(second_part) {
Ok(n) => second.push(n),
Err(err) => {
eprintln!("Failed to parse second number from {}: {}", second_part, err);
}
}
}
}
let mut second_counts = HashMap::<i64, i64>::new();
for element in second {
*second_counts.entry(element).or_insert(0) += 1;
}
let result = first.iter().map(|num| num * second_counts.get(num).unwrap_or(&0)).sum::<i64>();
println!("Similarity: {}", result);
}