Решение на упр.05 задача 2 от Ивайло Иванов
Резултати
- 3 точки от тестове
- 0 бонус точки
- 3 точки общо
- 3 успешни тест(а)
- 0 неуспешни тест(а)
Код
use std::{collections::HashMap, hash::Hash};
use std::fmt;
pub fn average(values: &[f64]) -> f64 {
if values.is_empty() {
0.0
} else {
values.iter().sum::<f64>() / values.len() as f64
}
}
struct Event {
timestamp: u64,
sensor: String,
metric: SensorMetric,
value: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum SensorMetric {
Load,
Frequency,
Temperature,
}
//Имплементация на Display за да можем да превърнем SensorMetric енума в низ за резултата от TotalAggregator
impl fmt::Display for SensorMetric {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
SensorMetric::Load => "Load",
SensorMetric::Frequency => "Frequency",
SensorMetric::Temperature => "Temperature",
};
write!(f, "{s}")
}
}
fn group_and_aggregate<O, E, D, K>(
events: &[E],
group_fn: impl Fn(&E) -> K,
data_fn: impl Fn(&E) -> Option<D>,
aggregate: impl Fn(&[D]) -> O,
) -> HashMap<K, O>
where
K: Eq + Hash,
{
let mut groups: HashMap<K, Vec<D>> = HashMap::new();
for event in events {
if let Some(data) = data_fn(event) {
groups.entry(group_fn(event)).or_default().push(data);
}
}
let mut result: HashMap<K, O> = HashMap::new();
for (key, dataArr) in groups {
let agg = aggregate(&dataArr);
result.insert(key, agg);
}
result
}
trait Aggregator {
type Output;
fn name(&self) -> String;
fn aggregate(&self, events: &[Event]) -> Vec<(String, Self::Output)>;
}
struct TotalAggregator {}
impl Aggregator for TotalAggregator {
type Output = f64;
fn name(&self) -> String {
"total".to_string()
}
fn aggregate(&self, events: &[Event]) -> Vec<(String, f64)> {
//връщаме HashMap<SenMetric, value> където value е средната от
//стойностите извлечени от евентите, на този мап му взимаме итератор и с collect правим вектор от него
group_and_aggregate(&events, |e| e.metric.to_string(), |e| Some(e.value), average)
.into_iter()
.collect()
}
}
struct MetricAggregator {
metric: SensorMetric
}
impl Aggregator for MetricAggregator {
type Output = f64;
fn name(&self) -> String {
format!("{:?}", self.metric)
}
fn aggregate(&self, events: &[Event]) -> Vec<(String, f64)> {
//ссъщото като горниа aggregate, само където тук ключовете са сензорите
//и извличаме стойностите за метриката, която ни интересува
group_and_aggregate(&events,
|e| e.sensor.clone(),
|e| {
if self.metric == e.metric {
Some(e.value)
} else {
None
}
}, average)
.into_iter()
.collect()
}
}
Лог от изпълнението
Updating crates.io index
Locking 17 packages to latest compatible versions
Compiling proc-macro2 v1.0.103
Compiling unicode-ident v1.0.22
Compiling quote v1.0.42
Compiling futures-core v0.3.31
Compiling futures-sink v0.3.31
Compiling futures-channel v0.3.31
Compiling memchr v2.7.6
Compiling syn v2.0.110
Compiling pin-project-lite v0.2.16
Compiling futures-task v0.3.31
Compiling futures-io v0.3.31
Compiling pin-utils v0.1.0
Compiling slab v0.4.11
Compiling solution v0.1.0 (/tmp/d20251113-1757769-5coag8/solution)
warning: struct `Event` is never constructed
--> src/lib.rs:12:8
|
12 | struct Event {
| ^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: enum `SensorMetric` is never used
--> src/lib.rs:20:6
|
20 | enum SensorMetric {
| ^^^^^^^^^^^^
warning: function `group_and_aggregate` is never used
--> src/lib.rs:38:4
|
38 | fn group_and_aggregate<O, E, D, K>(
| ^^^^^^^^^^^^^^^^^^^
warning: trait `Aggregator` is never used
--> src/lib.rs:64:7
|
64 | trait Aggregator {
| ^^^^^^^^^^
warning: struct `TotalAggregator` is never constructed
--> src/lib.rs:71:8
|
71 | struct TotalAggregator {}
| ^^^^^^^^^^^^^^^
warning: struct `MetricAggregator` is never constructed
--> src/lib.rs:89:8
|
89 | struct MetricAggregator {
| ^^^^^^^^^^^^^^^^
warning: variable `dataArr` should have a snake case name
--> src/lib.rs:56:15
|
56 | for (key, dataArr) in groups {
| ^^^^^^^ help: convert the identifier to snake case: `data_arr`
|
= note: `#[warn(non_snake_case)]` on by default
warning: `solution` (lib) generated 7 warnings
Compiling futures-macro v0.3.31
Compiling futures-util v0.3.31
Compiling futures-executor v0.3.31
Compiling futures v0.3.31
warning: field `timestamp` is never read
--> tests/../src/lib.rs:13:5
|
12 | struct Event {
| ----- field in this struct
13 | timestamp: u64,
| ^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: method `name` is never used
--> tests/../src/lib.rs:67:8
|
64 | trait Aggregator {
| ---------- method in this trait
...
67 | fn name(&self) -> String;
| ^^^^
warning: variable `dataArr` should have a snake case name
--> tests/../src/lib.rs:56:15
|
56 | for (key, dataArr) in groups {
| ^^^^^^^ help: convert the identifier to snake case: `data_arr`
|
= note: `#[warn(non_snake_case)]` on by default
warning: `solution` (test "solution_test") generated 3 warnings
Finished `test` profile [unoptimized + debuginfo] target(s) in 8.79s
Running tests/solution_test.rs (target/debug/deps/solution_test-f75e629a1d90e17c)
running 3 tests
test solution_test::test_by_metric ... ok
test solution_test::test_by_metric_2 ... ok
test solution_test::test_total ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
