diff --git a/rust/src/bin/single_thread.rs b/rust/src/bin/single_thread.rs new file mode 100644 index 0000000..a515ef7 --- /dev/null +++ b/rust/src/bin/single_thread.rs @@ -0,0 +1,56 @@ +use std::{ + collections::HashMap, + fs::File, + io::{BufRead, BufReader}, +}; + +struct StationMeasurements { + min: f64, + max: f64, + temps: Vec, +} + +fn main() { + let mut stations: HashMap = HashMap::new(); + + let file = File::open("../measurements.txt").expect("File measurements.txt not found"); + let reader = BufReader::new(file); + let mut line_num = 0; + for line_result in reader.lines() { + line_num += 1; + if line_num % 50000 == 0 { + println!("Calculated {line_num} stations"); + } + let line = line_result.expect("could not read line"); + let (station, temp) = line.split_once(';').unwrap(); + let temp = temp.parse().unwrap(); + let measurements_option = stations.get_mut(station); + if let Some(measurements) = measurements_option { + if temp < measurements.min { + measurements.min = temp; + } else if temp > measurements.max { + measurements.max = temp; + } + measurements.temps.push(temp); + } else { + let measurements = StationMeasurements { + min: temp, + max: temp, + temps: vec![temp], + }; + stations.insert(station.to_owned(), measurements); + } + } + for (station, measurments) in stations { + let min = measurments.min; + let max = measurments.max; + let avg = avg(measurments.temps); + println!("{station}={min}/{max}/{avg}"); + } +} + +fn avg(temps: Vec) -> f64 { + let num_temps = temps.len() as f64; + let sum_temps: f64 = temps.iter().sum(); + sum_temps / num_temps +}