diff options
| author | hybrid <hybrid@hybridlabs.cc> | 2026-10-14 21:33:16 +0300 |
|---|---|---|
| committer | hybrid <hybrid@hybridlabs.cc> | 2026-10-14 21:33:16 +0300 |
| commit | 43ddbb814e679bf2adde3a8602624c207641dca2 (patch) | |
| tree | b2cc74f6827381bc29608a3143f6131b19477535 /src/hashmaps_01 | |
| parent | 84fe604d3492420821e7afc0772c6d2fb4c2e046 (diff) | |
| download | rust-book-43ddbb814e679bf2adde3a8602624c207641dca2.tar.gz rust-book-43ddbb814e679bf2adde3a8602624c207641dca2.tar.bz2 rust-book-43ddbb814e679bf2adde3a8602624c207641dca2.zip | |
add: libs/restaurant, src/{hashmaps_01, piglatin}
Diffstat (limited to '')
| -rw-r--r-- | src/hashmaps_01/Cargo.toml | 6 | ||||
| -rw-r--r-- | src/hashmaps_01/src/main.rs | 79 |
2 files changed, 85 insertions, 0 deletions
diff --git a/src/hashmaps_01/Cargo.toml b/src/hashmaps_01/Cargo.toml new file mode 100644 index 0000000..d02c5c5 --- /dev/null +++ b/src/hashmaps_01/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "hashmaps_01" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/hashmaps_01/src/main.rs b/src/hashmaps_01/src/main.rs new file mode 100644 index 0000000..00f1dea --- /dev/null +++ b/src/hashmaps_01/src/main.rs @@ -0,0 +1,79 @@ +/* + * Chapter: + * 8.3 Storing Keys with assosiated Values in Hash Maps + * + * Link: + * https://doc.rust-lang.org/stable/book/ch08-03-hash-maps.html#summary + * + * Task: + * Given a list of integers, use a vector and return the average, the median + * (when sorted, the value in the middle position) and mode + * (the value that occurs most often; a hash map will be helpful here) + * of the list. + * + * Remark: + * - Average task is from russian translated version of the book. + */ + +fn main() { + let v = vec![ + 10, 10, 10, 9, 8, + 7, 6, 5, 4, 3, 2, + 1, 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9, 10, + ]; + // sorted: 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, + // 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 10 + + println!("avg: {:.2}", avg(&v)); + println!("median: {:.2}", median(&v)); + println!("mode: {}", mode(&v)); +} + +fn avg(v: &[i32]) -> f64 { + if v.is_empty() { + return 0.0; + } + let mut sum: f64 = 0.0; + + for i in 0..v.len() { + sum += v[i] as f64; + } + + sum / v.len() as f64 +} + +fn median(v: &[i32]) -> i32 { + let mut sorted = v.to_vec(); + sorted.sort(); + + let n = sorted.len(); + + if n % 2 == 1 { + sorted[n / 2] + } else { + ((sorted[n / 2 - 1] as i64 + sorted[n / 2] as i64) / 2) as i32 + } +} + +fn mode(v: &[i32]) -> i32 { + use std::collections::HashMap; + + let mut counts = HashMap::new(); + + for &i in v { + let _ = *counts.entry(i).or_insert(0) += 1; + } + + let mut max_key = v[0]; + let mut max_count = 0; + + for (&key, &count) in &counts { + if count > max_count { + max_key = key; + max_count = count; + } + } + + max_key +} |
