Решение на упр.05 задача 2 от Нели Илиева

Обратно към всички решения

Към профила на Нели Илиева

Резултати

  • 2 точки от тестове
  • 0 бонус точки
  • 2 точки общо
  • 2 успешни тест(а)
  • 1 неуспешни тест(а)

Код

use std::collections::HashMap;
use std::hash::Hash;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum SensorMetric {
Load,
Frequency,
Temperature,
}
struct Event {
timestamp: u64,
sensor: String,
metric: SensorMetric,
value: f64,
}
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 e in events {
if let Some(data) = data_fn(e) {
let key = group_fn(e);
groups.entry(key).or_insert_with(Vec::new).push(data);
}
}
groups.into_iter().map(|(key, data)| (key, aggregate(&data))).collect()
}
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)> {
let res = group_and_aggregate(
events,
|event| event.metric,
|event| Some(event.value),
|values| {
if values.is_empty() {
0.0
}
else {
values.iter().sum::<f64>() / values.len() as f64
}
},
);
res.into_iter().map(|(metric, avg)| (format!("{:?}", metric), avg)).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)> {
let filtered_events: Vec<&Event> = events
.iter()
.filter(|event| event.metric == self.metric)
.collect();
let res = group_and_aggregate(
&filtered_events,
|event| event.sensor.clone(),
|event| Some(event.value),
|values| values.iter().sum::<f64>(),
);
res.into_iter().collect()
}
}

Лог от изпълнението

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-project-lite v0.2.16
   Compiling futures-io v0.3.31
   Compiling syn v2.0.110
   Compiling futures-task v0.3.31
   Compiling slab v0.4.11
   Compiling pin-utils v0.1.0
   Compiling memchr v2.7.6
   Compiling solution v0.1.0 (/tmp/d20251113-1757769-1pdxgm8/solution)
warning: enum `SensorMetric` is never used
 --> src/lib.rs:5:6
  |
5 | enum SensorMetric {
  |      ^^^^^^^^^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: struct `Event` is never constructed
  --> src/lib.rs:11:8
   |
11 | struct Event {
   |        ^^^^^

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:39:7
   |
39 | trait Aggregator {
   |       ^^^^^^^^^^

warning: struct `TotalAggregator` is never constructed
  --> src/lib.rs:46:8
   |
46 | struct TotalAggregator {}
   |        ^^^^^^^^^^^^^^^

warning: struct `MetricAggregator` is never constructed
  --> src/lib.rs:74:8
   |
74 | 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:12:5
   |
11 | struct Event {
   |        ----- field in this struct
12 |     timestamp: u64,
   |     ^^^^^^^^^
   |
   = note: `#[warn(dead_code)]` on by default

warning: method `name` is never used
  --> tests/../src/lib.rs:42:8
   |
39 | trait Aggregator {
   |       ---------- method in this trait
...
42 |     fn name(&self) -> String;
   |        ^^^^

warning: `solution` (test "solution_test") generated 2 warnings
    Finished `test` profile [unoptimized + debuginfo] target(s) in 8.89s
     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`

История (1 версия и 0 коментара)

Нели качи първо решение на 10.11.2025 18:42 (преди 26 дена)