Skip to content

Instantly share code, notes, and snippets.

@skoji
Last active April 28, 2018 13:15
Show Gist options
  • Save skoji/25928bfe60565a48cc44b7a5c9f84bf5 to your computer and use it in GitHub Desktop.
Save skoji/25928bfe60565a48cc44b7a5c9f84bf5 to your computer and use it in GitHub Desktop.
// 参考: https://codereview.stackexchange.com/questions/173338/calculate-mean-median-and-mode-in-rust
use std::collections::HashMap;
fn mean(data : &Vec<i32>) -> f32 {
let mut r = 0;
for i in data {
r = r + i;
}
r as f32 / data.len() as f32
}
fn median(data: &Vec<i32>) -> i32 {
let mut work = data.clone();
work.sort();
work[data.len() / 2]
}
fn mode(data: &Vec<i32>) -> (i32, i32) {
let mut map:HashMap<&i32, i32> = HashMap::new();
for i in data {
let count = map.entry(i).or_insert(0);
*count += 1;
}
let mut count_vec: Vec<(&&i32,&i32)> = map.iter().collect();
count_vec.sort_by(|a,b| b.1.cmp(a.1));
(**count_vec[0].0, *count_vec[0].1) // I do not think this is not optimal...
}
fn main() {
let d = vec![9,129,53,899,1,2,4,4,31,9,129,53,53];
println!("mean: {}", mean(&d));
println!("median: {}", median(&d));
let m = mode(&d);
println!("mode: {} ( {} times )", m.0, m.1);
}
fn piglatin(s: &str) -> String {
let s = s.to_string();
let mut si = s.chars();
let mut post = String::new();
let mut pre = String::new();
while let Some(c) = si.next() {
match c {
'a' | 'e' | 'i' | 'o' | 'u' => {
pre.push(c);
break;
}
_ => {
post.push(c);
}
}
}
let s : String = si.collect();
pre = pre + s.as_str();
if post.len() == 0 {
post.push('h');
}
format!("{}-{}ay",pre, post)
}
fn main() {
println!("{}", piglatin("apple"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment