summaryrefslogtreecommitdiff
path: root/mathsssss/src
diff options
context:
space:
mode:
authorAdam Carpenter <adam.carpenter@adp.com>2019-02-11 16:59:01 -0500
committerAdam Carpenter <adam.carpenter@adp.com>2019-02-11 16:59:01 -0500
commitef1bf4921ee4127d461eec03a14c9070d193345c (patch)
treeab9f4ed73fcf97656743c959ce8c9adbe2ce9924 /mathsssss/src
downloadlearning-rust-ef1bf4921ee4127d461eec03a14c9070d193345c.tar.xz
learning-rust-ef1bf4921ee4127d461eec03a14c9070d193345c.zip
Init.
Diffstat (limited to 'mathsssss/src')
-rw-r--r--mathsssss/src/main.rs61
1 files changed, 61 insertions, 0 deletions
diff --git a/mathsssss/src/main.rs b/mathsssss/src/main.rs
new file mode 100644
index 0000000..991590b
--- /dev/null
+++ b/mathsssss/src/main.rs
@@ -0,0 +1,61 @@
+use std::env;
+use std::collections::HashMap;
+
+fn calc_mean(numbers: &Vec<i32>) -> f32 {
+ let sum: i32 = numbers.iter().sum();
+ sum as f32 / numbers.len() as f32
+}
+
+fn calc_median(numbers: &Vec<i32>) -> i32 {
+ numbers[numbers.len() / 2]
+}
+
+fn calc_mode(numbers: &Vec<i32>) -> i32 {
+ let mut counts: HashMap<i32, i32> = HashMap::new();
+
+ for each in numbers {
+ let count = counts.entry(*each).or_insert(0);
+ *count += 1;
+ }
+
+ let mut most: i32 = 0;
+ let mut result: i32 = 0;
+
+ for (key, val) in counts.iter() {
+
+ if val > &most {
+ most = *val;
+ result = *key;
+ }
+ }
+
+ if most <= 1 {
+ 0
+ }
+ else {
+ result
+ }
+
+}
+
+fn main() {
+ // grab numbers
+ let mut numbers: Vec<i32> = Vec::new();
+
+ for arg in env::args().skip(1) {
+ let number: i32 = arg.trim().parse()
+ .expect("error: could not parse arg");
+ numbers.push(number);
+ }
+
+ // sort list (mostly for median)
+ numbers.sort_by(|a, b| a.partial_cmp(b).unwrap());
+
+ // calculate and print results
+ let mean: f32 = calc_mean(&numbers);
+ println!("mean: {}", mean);
+ let median: i32 = calc_median(&numbers);
+ println!("median: {}", median);
+ let mode: i32 = calc_mode(&numbers);
+ println!("mode: {}", mode);
+}