• 1 Post
  • 178 Comments
Joined 1 year ago
cake
Cake day: June 27th, 2023

help-circle







  • 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

    use std::collections::HashMap; 
    struct Statistics { numbers: Vec, } 
    
    impl Statistics { fn new(numbers: Vec) -> Self { Statistics { numbers } } fn mean(&self) -> Option { 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 { 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 { 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, as they may not be applicable (for example, if the array of numbers is empty).