rust_learning/numbers/src/main.rs

74 lines
1.9 KiB
Rust

use std::collections::HashMap;
fn get_mean(input: &Vec<i32>) -> f64 {
let mut total = 0;
for n in input {
total += n;
}
total as f64 / input.len() as f64
}
fn get_median(input: &Vec<i32>) -> f64 {
let mut tmp = input.clone();
let mut i: usize = 0;
while i < tmp.len() - 1 {
if &tmp[i] > &tmp[i + 1] {
tmp.swap(i, i + 1);
} else {
i += 1;
}
}
if tmp.len() % 2 == 1 {
tmp[tmp.len() / 2] as f64
} else {
(tmp[tmp.len() / 2 - 1] + tmp[tmp.len() / 2]) as f64 / 2.0
}
}
fn get_mode(input: &Vec<i32>) -> Option<i32> {
let mut map = HashMap::new();
let mut max: (Option<i32>, Option<i32>) = (None, None);
let mut none = true;
for &n in input {
let count = map.entry(n).or_insert(0);
*count += 1;
}
for (&key, &value) in &map {
if Some(value) > max.1 {
max = (Some(key), Some(value));
none = false;
} else if Some(value) == max.1 {
none = true;
}
}
if none {
None
} else {
max.0
}
}
fn main() {
let input1: Vec<i32> = vec![-23, 46, 10, 45, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 23, 46, 23, 23, 10, 12, 94];
let input2: Vec<i32> = vec![1, 2, 3, 4];
println!("Vec input1 : {:?}", input1);
println!("Average of input1 is {}", get_mean(&input1));
println!("Median of input1 is {}", get_median(&input1));
match get_mode(&input1) {
Some(v) => println!("Mode of input1 is {:?}", v),
None => println!("input1 has no mode."),
}
println!("Vec input2 : {:?}", input2);
println!("Average of input2 is {}", get_mean(&input2));
println!("Median of input2 is {}", get_median(&input2));
match get_mode(&input2) {
Some(v) => println!("Mode of input2 is {:?}", v),
None => println!("input2 has no mode."),
}
}