Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::collections::HashMap;
- use std::fs::File;
- use std::io::{BufRead, BufReader};
- use std::time::Instant;
- fn create_sorted_vectors_from_file(
- file_name: &str,
- ) -> Result<(Vec<i32>, Vec<i32>), std::io::Error> {
- let file = File::open(file_name)?;
- let reader = BufReader::new(file);
- let mut col1 = Vec::new();
- let mut col2 = Vec::new();
- for line in reader.lines() {
- let line = line?;
- let numbers: Vec<i32> = line
- .split_whitespace()
- .map(|s| s.parse().unwrap())
- .collect();
- if numbers.len() == 2 {
- col1.push(numbers[0]);
- col2.push(numbers[1]);
- }
- }
- col1.sort();
- col2.sort();
- Ok((col1, col2))
- }
- fn calculate_l1_distance(vec1: &[i32], vec2: &[i32]) -> i64 {
- vec1.iter()
- .zip(vec2.iter())
- .map(|(a, b)| (a - b).abs() as i64)
- .sum()
- }
- fn find_similarity_score(vec1: &[i32], vec2: &[i32]) -> i64 {
- let mut vec2_counter: HashMap<i32, u32> = HashMap::new();
- for &el in vec2 {
- *vec2_counter.entry(el).or_insert(0) += 1;
- }
- let mut score = 0i64;
- for el in vec1 {
- if let Some(&count) = vec2_counter.get(el) {
- score += (el.clone() as i64) * (count as i64)
- }
- }
- score
- }
- fn main() {
- let start = Instant::now();
- match create_sorted_vectors_from_file("input.txt") {
- Ok((col1, col2)) => {
- if col1.len() == col2.len() {
- let l1_distance = calculate_l1_distance(&col1, &col2);
- let similarity_score = find_similarity_score(&col1, &col2);
- println!("L1 distance between the two vectors: {}", l1_distance);
- println!(
- "similarity score between the two vectors: {}",
- similarity_score
- );
- } else {
- println!("Error: Vectors have different lengths");
- }
- }
- Err(e) => println!("Error reading file: {}", e),
- }
- let duration = start.elapsed();
- println!("Time elapsed: {:?}", duration);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement