summaryrefslogtreecommitdiff
path: root/rust-book/mathsssss
diff options
context:
space:
mode:
authorAdam Carpenter <53hornet@gmail.com>2019-03-27 15:32:37 -0400
committerAdam Carpenter <53hornet@gmail.com>2019-03-27 15:32:37 -0400
commit67cdcc2e12118becb823e20a40cc2687f2b8425a (patch)
treeed92c3234b89079e6d4cf36f5e80c5ffa79def48 /rust-book/mathsssss
parente25482fca375d318a39c3b54db396b0db6e0b263 (diff)
downloadlearning-rust-67cdcc2e12118becb823e20a40cc2687f2b8425a.tar.xz
learning-rust-67cdcc2e12118becb823e20a40cc2687f2b8425a.zip
Started Rust in Action MEAP.
Diffstat (limited to 'rust-book/mathsssss')
-rwxr-xr-xrust-book/mathsssss/Cargo.lock4
-rwxr-xr-xrust-book/mathsssss/Cargo.toml7
-rwxr-xr-xrust-book/mathsssss/src/main.rs61
3 files changed, 72 insertions, 0 deletions
diff --git a/rust-book/mathsssss/Cargo.lock b/rust-book/mathsssss/Cargo.lock
new file mode 100755
index 0000000..7ef6f32
--- /dev/null
+++ b/rust-book/mathsssss/Cargo.lock
@@ -0,0 +1,4 @@
+[[package]]
+name = "mathsssss"
+version = "0.1.0"
+
diff --git a/rust-book/mathsssss/Cargo.toml b/rust-book/mathsssss/Cargo.toml
new file mode 100755
index 0000000..201c096
--- /dev/null
+++ b/rust-book/mathsssss/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "mathsssss"
+version = "0.1.0"
+authors = ["Adam Carpenter <adam.carpenter@adp.com>"]
+edition = "2018"
+
+[dependencies]
diff --git a/rust-book/mathsssss/src/main.rs b/rust-book/mathsssss/src/main.rs
new file mode 100755
index 0000000..991590b
--- /dev/null
+++ b/rust-book/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);
+}