Last active
May 16, 2022 17:58
-
-
Save kriogenia/dde03043b31b58611b142ca8f2a11b79 to your computer and use it in GitHub Desktop.
Generics on Rust - StudentRecord Non-Generic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashMap; | |
pub struct StudentRecord { | |
student_id: u32, | |
marks: Vec<u8>, | |
} | |
impl StudentRecord { | |
pub fn new(student_id: u32) -> Self { | |
Self { | |
student_id, | |
marks: Vec::new(), | |
} | |
} | |
pub fn add_mark(&mut self, mark: u8) { | |
self.marks.push(mark); | |
} | |
pub fn avg(&self) -> u8 { | |
let mut sum = 0; | |
for mark in &self.marks { | |
sum += mark; | |
} | |
sum.checked_div(self.marks.len() as u8).expect("No marks") | |
} | |
pub fn mode(&self) -> u8 { | |
let mut map = HashMap::new(); | |
for mark in &self.marks { | |
*map.entry(mark).or_insert(0) += 1; | |
} | |
*map | |
.into_iter() | |
.max_by_key(|&(_, count)| count) | |
.map(|(mark, _)| mark) | |
.expect("No marks") | |
} | |
pub fn median(&mut self) -> u8 { | |
self.marks.sort(); | |
*self.marks.get(self.marks.len() / 2).expect("No marks") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment