Advertisement
msminhas93

aoc_2024_day1_rust

Dec 4th, 2024
390
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.12 KB | None | 0 0
  1. use std::collections::HashMap;
  2. use std::fs::File;
  3. use std::io::{BufRead, BufReader};
  4. use std::time::Instant;
  5.  
  6. fn create_sorted_vectors_from_file(
  7.     file_name: &str,
  8. ) -> Result<(Vec<i32>, Vec<i32>), std::io::Error> {
  9.     let file = File::open(file_name)?;
  10.     let reader = BufReader::new(file);
  11.  
  12.     let mut col1 = Vec::new();
  13.     let mut col2 = Vec::new();
  14.  
  15.     for line in reader.lines() {
  16.         let line = line?;
  17.         let numbers: Vec<i32> = line
  18.             .split_whitespace()
  19.             .map(|s| s.parse().unwrap())
  20.             .collect();
  21.  
  22.         if numbers.len() == 2 {
  23.             col1.push(numbers[0]);
  24.             col2.push(numbers[1]);
  25.         }
  26.     }
  27.  
  28.     col1.sort();
  29.     col2.sort();
  30.  
  31.     Ok((col1, col2))
  32. }
  33.  
  34. fn calculate_l1_distance(vec1: &[i32], vec2: &[i32]) -> i64 {
  35.     vec1.iter()
  36.         .zip(vec2.iter())
  37.         .map(|(a, b)| (a - b).abs() as i64)
  38.         .sum()
  39. }
  40.  
  41. fn find_similarity_score(vec1: &[i32], vec2: &[i32]) -> i64 {
  42.     let mut vec2_counter: HashMap<i32, u32> = HashMap::new();
  43.     for &el in vec2 {
  44.         *vec2_counter.entry(el).or_insert(0) += 1;
  45.     }
  46.     let mut score = 0i64;
  47.     for el in vec1 {
  48.         if let Some(&count) = vec2_counter.get(el) {
  49.             score += (el.clone() as i64) * (count as i64)
  50.         }
  51.     }
  52.     score
  53. }
  54. fn main() {
  55.     let start = Instant::now();
  56.     match create_sorted_vectors_from_file("input.txt") {
  57.         Ok((col1, col2)) => {
  58.             if col1.len() == col2.len() {
  59.                 let l1_distance = calculate_l1_distance(&col1, &col2);
  60.                 let similarity_score = find_similarity_score(&col1, &col2);
  61.                 println!("L1 distance between the two vectors: {}", l1_distance);
  62.                 println!(
  63.                     "similarity score between the two vectors: {}",
  64.                     similarity_score
  65.                 );
  66.             } else {
  67.                 println!("Error: Vectors have different lengths");
  68.             }
  69.         }
  70.         Err(e) => println!("Error reading file: {}", e),
  71.     }
  72.     let duration = start.elapsed();
  73.     println!("Time elapsed: {:?}", duration);
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement