Решение на упр.05 задача 2 от Георги Стоянов
Резултати
- 2 точки от тестове
- 0 бонус точки
- 2 точки общо
- 2 успешни тест(а)
- 1 неуспешни тест(а)
Код
use std::hash::Hash;
use std::collections::HashMap;
struct Event {
timestamp: u64,
sensor: String,
metric: SensorMetric,
value: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum SensorMetric {
Load,
Frequency,
Temperature,
}
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 buckets: HashMap<K, Vec<D>> = HashMap::new();
for e in events {
if let Some(d) = data_fn(e) {
buckets.entry(group_fn(e)).or_default().push(d);
}
}
buckets
.into_iter()
.map(|(k, v)| (k, aggregate(&v)))
.collect()
}
trait Aggregator {
type Output;
fn name(&self) -> String;
fn aggregate(&self, events: &[Event]) -> Vec<(String, Self::Output)>;
}
// Имплементирайте агрегация, която връща средната стойност на метриките, групирани по тип.
// Резултата трябва да е вектор от три елемента:
// - ("Load", <средната стойност на Load метриките от всички сензори>)
// - ("Frequency", <средната стойност на Frequency метриките от всички сензори>)
// - ("Temperature", <средната стойност на Temperature метриките от всички сензори>)
struct TotalAggregator {}
impl Aggregator for TotalAggregator {
type Output = f64;
fn name(&self) -> String {
"total".to_string()
}
fn aggregate(&self, events: &[Event]) -> Vec<(String, f64)> {
let by_metric: HashMap<SensorMetric, f64> = group_and_aggregate(
events,
|e| e.metric,
|e| Some(e.value),
|vals| {
let sum: f64 = vals.iter().copied().sum();
sum / (vals.len() as f64)
},
);
let order = [SensorMetric::Load, SensorMetric::Frequency, SensorMetric::Temperature];
order
.into_iter()
.map(|m| (format!("{:?}", m), *by_metric.get(&m).unwrap_or(&0.0)))
.collect()
}
}
// Имплементирайте агрегация, която по даден тип на метрика, връща сумата от метриките
// от този тип, групирани по сензор.
// Пример при `MetricAggreator { metric: SensorMetric::Load }`, може да върне:
// - ("cpu0", <средната стойност от Load метиките за сензор cpu0>)
// - ("cpu1", <средната стойност от Load метиките за сензор cpu1>)
// - ("gpu0", <средната стойност от Load метиките за сензор gpu0>)
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)> {
let sums: HashMap<String, f64> = group_and_aggregate(
events,
|e| e.sensor.clone(),
|e| (e.metric == self.metric).then_some(e.value),
|vals| vals.iter().copied().sum::<f64>(),
);
let mut out: Vec<(String, f64)> = sums.into_iter().collect();
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
}
Лог от изпълнението
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 pin-utils v0.1.0
Compiling futures-io v0.3.31
Compiling syn v2.0.110
Compiling memchr v2.7.6
Compiling futures-task v0.3.31
Compiling pin-project-lite v0.2.16
Compiling slab v0.4.11
Compiling solution v0.1.0 (/tmp/d20251113-1757769-2tm4fw/solution)
warning: struct `Event` is never constructed
--> src/lib.rs:4:8
|
4 | struct Event {
| ^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: enum `SensorMetric` is never used
--> src/lib.rs:12:6
|
12 | enum SensorMetric {
| ^^^^^^^^^^^^
warning: function `group_and_aggregate` is never used
--> src/lib.rs:18:4
|
18 | fn group_and_aggregate<O, E, D, K>(
| ^^^^^^^^^^^^^^^^^^^
warning: trait `Aggregator` is never used
--> src/lib.rs:41:7
|
41 | trait Aggregator {
| ^^^^^^^^^^
warning: struct `TotalAggregator` is never constructed
--> src/lib.rs:53:8
|
53 | struct TotalAggregator {}
| ^^^^^^^^^^^^^^^
warning: struct `MetricAggregator` is never constructed
--> src/lib.rs:86:8
|
86 | struct MetricAggregator {
| ^^^^^^^^^^^^^^^^
warning: `solution` (lib) generated 6 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:5:5
|
4 | struct Event {
| ----- field in this struct
5 | timestamp: u64,
| ^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: method `name` is never used
--> tests/../src/lib.rs:44:8
|
41 | trait Aggregator {
| ---------- method in this trait
...
44 | fn name(&self) -> String;
| ^^^^
warning: `solution` (test "solution_test") generated 2 warnings
Finished `test` profile [unoptimized + debuginfo] target(s) in 9.13s
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 ... FAILED
test solution_test::test_total ... ok
failures:
---- solution_test::test_by_metric_2 stdout ----
thread 'solution_test::test_by_metric_2' panicked at tests/solution_test.rs:89:5:
assertion `left == right` failed
left: [("gpu0", FloatApprox(14.469999999999999))]
right: [("gpu0", FloatApprox(4.83))]
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
solution_test::test_by_metric_2
test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--test solution_test`
История (2 версии и 0 коментара)
Георги качи решение на 10.11.2025 15:04 (преди 26 дена)
use std::hash::Hash;
use std::collections::HashMap;
struct Event {
timestamp: u64,
sensor: String,
metric: SensorMetric,
value: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum SensorMetric {
Load,
Frequency,
Temperature,
}
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 buckets: HashMap<K, Vec<D>> = HashMap::new();
for e in events {
if let Some(d) = data_fn(e) {
buckets.entry(group_fn(e)).or_default().push(d);
}
}
buckets
.into_iter()
.map(|(k, v)| (k, aggregate(&v)))
.collect()
}
trait Aggregator {
type Output;
fn name(&self) -> String;
fn aggregate(&self, events: &[Event]) -> Vec<(String, Self::Output)>;
}
// Имплементирайте агрегация, която връща средната стойност на метриките, групирани по тип.
// Резултата трябва да е вектор от три елемента:
// - ("Load", <средната стойност на Load метриките от всички сензори>)
// - ("Frequency", <средната стойност на Frequency метриките от всички сензори>)
// - ("Temperature", <средната стойност на Temperature метриките от всички сензори>)
struct TotalAggregator {}
impl Aggregator for TotalAggregator {
type Output = f64;
fn name(&self) -> String {
"total".to_string()
}
fn aggregate(&self, events: &[Event]) -> Vec<(String, f64)> {
- // group by metric, average value within each metric
let by_metric: HashMap<SensorMetric, f64> = group_and_aggregate(
events,
- |e| e.metric, // key: SensorMetric
- |e| Some(e.value), // data: f64 values
+ |e| e.metric,
+ |e| Some(e.value),
|vals| {
let sum: f64 = vals.iter().copied().sum();
sum / (vals.len() as f64)
},
);
- // produce stable order: Load, Frequency, Temperature
let order = [SensorMetric::Load, SensorMetric::Frequency, SensorMetric::Temperature];
order
.into_iter()
.map(|m| (format!("{:?}", m), *by_metric.get(&m).unwrap_or(&0.0)))
.collect()
}
}
// Имплементирайте агрегация, която по даден тип на метрика, връща сумата от метриките
// от този тип, групирани по сензор.
// Пример при `MetricAggreator { metric: SensorMetric::Load }`, може да върне:
// - ("cpu0", <средната стойност от Load метиките за сензор cpu0>)
// - ("cpu1", <средната стойност от Load метиките за сензор cpu1>)
// - ("gpu0", <средната стойност от Load метиките за сензор gpu0>)
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)> {
- // only keep events with the chosen metric; group by sensor; sum values
let sums: HashMap<String, f64> = group_and_aggregate(
events,
- |e| e.sensor.clone(), // key: sensor id/name
+ |e| e.sensor.clone(),
|e| (e.metric == self.metric).then_some(e.value),
|vals| vals.iter().copied().sum::<f64>(),
);
- // stable, readable order by sensor name
let mut out: Vec<(String, f64)> = sums.into_iter().collect();
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
-}
+}
