1712321207

Rust, implemented in something real


Create a struct in Rust called Statistics that holds a list of numbers and implement methods to calculate these statistics. For example, you could have methods to calculate the mean, median and mode of the numbers stored in the structure. **The code** ```rust use std::collections::HashMap; struct Statistics { numbers: Vec<f64>, } impl Statistics { fn new(numbers: Vec<f64>) -> Self { Statistics { numbers } } fn mean(&self) -> Option<f64> { let sum: f64 = self.numbers.iter().sum(); let count = self.numbers.len() as f64; if count > 0 { Some(sum / count) } else { None } } fn median(&mut self) -> Option<f64> { self.numbers.sort_by(|a, b| a.partial_cmp(b).unwrap()); let len = self.numbers.len(); if len == 0 { return None; } if len % 2 == 0 { let mid = len / 2; Some((self.numbers[mid - 1] + self.numbers[mid]) / 2.0) } else { Some(self.numbers[len / 2]) } } fn mode(&self) -> Option<f64> { let mut map = HashMap::new(); for &num in &self.numbers { *map.entry(num).or_insert(0) += 1; } let max_value = map.values().max()?; let mode = map.iter().find(|&(_, &count)| count == *max_value)?; Some(*mode.0) } } fn main() { let numbers = vec![1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 6.0, 6.0, 6.0]; let stats = Statistics::new(numbers.clone()); println!("Numbers: {:?}", numbers); println!("Mean: {:?}", stats.mean()); println!("Median: {:?}", stats.median()); println!("Mode: {:?}", stats.mode()); } ``` This code creates the struct Statistics, which has a vector of numbers. It implements methods to calculate the mean, median and mode of these numbers. The mean method calculates the mean of the numbers, median calculates the median and mode calculates the mode. Note that these methods return Option<f64>, as they may not be applicable (for example, if the array of numbers is empty).

To comment this publication you need to be logged in.