Решение на упр.05 задача 2 от Стилиян Иванов
Резултати
- 3 точки от тестове
- 0 бонус точки
- 3 точки общо
- 3 успешни тест(а)
- 0 неуспешни тест(а)
Код
use std::collections::HashMap;
use std::hash::Hash;
#[derive(Debug, Clone)]
pub struct Event {
pub timestamp: u64,
pub sensor: String,
pub metric: SensorMetric,
pub value: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SensorMetric {
Load,
Frequency,
Temperature,
}
pub fn group_and_aggregate<O, E, D, K>(
events: &[E],
group_fn: impl Fn(&E) -> K,
data_fn: impl Fn(&E) -> Option<D>,
aggregate_fn: impl Fn(&[D]) -> O,
) -> HashMap<K, O>
where
K: Eq + Hash,
{
let mut intermediate_data = HashMap::new();
for event in events {
let key = group_fn(event);
if let Some(data) = data_fn(event) {
intermediate_data
.entry(key)
.or_insert_with(Vec::new)
.push(data);
}
}
let mut result = HashMap::new();
for (key, data_vec) in intermediate_data {
if !data_vec.is_empty() {
let aggregated_value = aggregate_fn(&data_vec);
result.insert(key, aggregated_value);
}
}
result
}
pub trait Aggregator {
type Output;
fn name(&self) -> String;
fn aggregate(&self, events: &[Event]) -> Vec<(String, Self::Output)>;
}
pub struct TotalAggregator {}
fn calculate_average(values: &[f64]) -> f64 {
if values.is_empty() {
0.0
} else {
values.iter().sum::<f64>() / (values.len() as f64)
}
}
impl Aggregator for TotalAggregator {
type Output = f64;
fn name(&self) -> String {
"total".to_string()
}
fn aggregate(&self, events: &[Event]) -> Vec<(String, f64)> {
let grouped_data = group_and_aggregate(
events,
|e| e.metric,
|e| Some(e.value),
calculate_average,
);
grouped_data
.into_iter()
.map(|(metric, avg_value)| (format!("{:?}", metric), avg_value))
.collect()
}
}
pub struct MetricAggregator {
pub metric: SensorMetric,
}
impl Aggregator for MetricAggregator {
type Output = f64;
fn name(&self) -> String {
format!("{:?}", self.metric)
}
fn aggregate(&self, events: &[Event]) -> Vec<(String, f64)> {
let grouped_data = group_and_aggregate(
events,
|e| e.sensor.clone(),
|e| {
if e.metric == self.metric {
Some(e.value)
} else {
None
}
},
calculate_average,
);
grouped_data.into_iter().collect()
}
}
fn main() {
let all: Vec<Box<dyn Aggregator<Output=f64>>> = vec![
Box::new(TotalAggregator{}),
Box::new(MetricAggregator{metric: SensorMetric::Load}),
Box::new(MetricAggregator{metric: SensorMetric::Temperature}),
];
let events = &[
Event { timestamp: 0, sensor: String::from("cpu0"), metric: SensorMetric::Load, value: 0.98 },
Event { timestamp: 0, sensor: String::from("cpu1"), metric: SensorMetric::Load, value: 0.04 },
Event { timestamp: 0, sensor: String::from("gpu0"), metric: SensorMetric::Load, value: 13.45 },
Event { timestamp: 0, sensor: String::from("cpu0"), metric: SensorMetric::Frequency, value: 3100.00 },
Event { timestamp: 0, sensor: String::from("cpu1"), metric: SensorMetric::Frequency, value: 3100.00 },
Event { timestamp: 0, sensor: String::from("gpu0"), metric: SensorMetric::Frequency, value: 300.00 },
Event { timestamp: 0, sensor: String::from("cpu0"), metric: SensorMetric::Temperature, value: 56.20 },
Event { timestamp: 0, sensor: String::from("cpu1"), metric: SensorMetric::Temperature, value: 33.33 },
Event { timestamp: 0, sensor: String::from("gpu0"), metric: SensorMetric::Temperature, value: 25.00 },
];
for aggr in &all {
for (key, val) in aggr.aggregate(events) {
println!("{} {:?}: {:.02}", aggr.name(), key, val);
}
}
// total "Temperature": 38.18
// total "Load": 4.82
// total "Frequency": 2166.67
// Load "gpu0": 13.45
// Load "cpu1": 0.04
// Load "cpu0": 0.98
// Temperature "cpu1": 33.33
// Temperature "cpu0": 56.20
// Temperature "gpu0": 25.00
}
Лог от изпълнението
Updating crates.io index
Locking 17 packages to latest compatible versions
Compiling proc-macro2 v1.0.103
Compiling quote v1.0.42
Compiling unicode-ident v1.0.22
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 slab v0.4.11
Compiling futures-io v0.3.31
Compiling pin-project-lite v0.2.16
Compiling futures-task v0.3.31
Compiling pin-utils v0.1.0
Compiling solution v0.1.0 (/tmp/d20251113-1757769-1sh3pdm/solution)
warning: function `main` is never used
--> src/lib.rs:117:4
|
117 | fn main() {
| ^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: `solution` (lib) generated 1 warning
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:6:9
|
5 | pub struct Event {
| ----- field in this struct
6 | pub timestamp: u64,
| ^^^^^^^^^
|
= note: `Event` has derived impls for the traits `Clone` and `Debug`, but these are intentionally ignored during dead code analysis
= note: `#[warn(dead_code)]` on by default
warning: method `name` is never used
--> tests/../src/lib.rs:53:8
|
51 | pub trait Aggregator {
| ---------- method in this trait
52 | type Output;
53 | fn name(&self) -> String;
| ^^^^
warning: function `main` is never used
--> tests/../src/lib.rs:117:4
|
117 | fn main() {
| ^^^^
warning: `solution` (test "solution_test") generated 3 warnings
Finished `test` profile [unoptimized + debuginfo] target(s) in 9.06s
Running tests/solution_test.rs (target/debug/deps/solution_test-f75e629a1d90e17c)
running 3 tests
test solution_test::test_by_metric_2 ... ok
test solution_test::test_by_metric ... 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
