"Rust mean, median, mode algorithms" Code Answer's

You're definitely familiar with the best coding language Rust that developers use to develop their projects and they get all their queries like "Rust mean, median, mode algorithms" answered properly. Developers are finding an appropriate answer about Rust mean, median, mode algorithms related to the Rust coding language. By visiting this online portal developers get answers concerning Rust codes question like Rust mean, median, mode algorithms. Enter your desired code related query in the search bar and get every piece of information about Rust code related question on Rust mean, median, mode algorithms.

Rust mean, median, mode algorithms

By Katonkel on Mar 14, 2021
``````// Rust mean, median, mode algorithms with examples of use
fn mean(arr: &[f64]) -> f64 {
let sum = arr.iter().fold(0.0, |p,&q| p + q);
sum / arr.len() as f64
}

fn median(mut xs: Vec<f64>) -> f64 {
// sort in ascending order, panic on f64::NaN
xs.sort_by(|x,y| x.partial_cmp(y).unwrap() );
let n = xs.len();
if n % 2 == 0 {
(xs[n/2] + xs[n/2 - 1]) / 2.0
} else {
xs[n/2]
}
}

fn mode(vs: Vec<i32>) -> Vec<i32> {
use std::collections::HashMap;
let mut vec_mode = Vec::new();
let mut seen_map = HashMap::new();
let mut max_val = 0;
for i in vs{
let ctr = seen_map.entry(i).or_insert(0);
*ctr += 1;
if *ctr > max_val{
max_val = *ctr;
}
}
for (key, val) in seen_map {
if val == max_val{
vec_mode.push(key);
}
}
vec_mode
}

fn main() {
let v = &[2.0, 3.0, 5.0, 7.0, 13.0, 21.0, 33.0, 54.0];
println!("mean of {:?}: {:?}", v, mean(v));

let w = &[];
println!("mean of {:?}: {:?}", w, mean(w));

println!("median of {:?}: {:?}", v, median(v.to_vec()));

let mode_vec1 = mode(vec![ 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]);
let mode_vec2 = mode(vec![ 1, 1, 2, 4, 4]);

println!("Mode of vec1 is: {:?}", mode_vec1);
println!("Mode of vec2 is: {:?}", mode_vec2);
}``````