Решение на упр.05 задача 2 от Ясин Йосифов

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

Към профила на Ясин Йосифов

Резултати

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

Код

use std::collections::HashMap;
use std::hash::Hash;
#[derive(Clone)]
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 out = HashMap::<K, O>::new();
let mut grouped_items = HashMap::<K, Vec<D>>::new();
for item in events {
if let Some(d) = data_fn(&item) {
let group = group_fn(&item);
match grouped_items.get_mut(&group) {
Some(g) => g.push(d),
None => {
let vec = vec![d];
grouped_items.insert(group, vec);
}
}
}
};
for (key, value) in grouped_items {
out.insert(key, aggregate(&value));
};
out
}
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 map = group_and_aggregate(events, |e: &Event| { e.metric }, |e: &Event| { Some(e.value) }, |d: &[f64]| {
let mut total: f64 = 0.0;
for i in d {
total += i;
}
total/(d.len() as f64)
}
);
let mut vec = Vec::<(String, f64)>::new();
for (key, value) in map {
vec.push((format!("{:?}", key), value))
};
vec
}
}
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 mut vec = Vec::<Event>::from(events);
vec.retain(|e| e.metric == self.metric);
let map = group_and_aggregate(&vec, |e: &Event| { e.sensor.clone() }, |e: &Event| { Some(e.value) }, |d: &[f64]| {
let mut total: f64 = 0.0;
for i in d {
total += i;
}
total/(d.len() as f64)
}
);
let mut vec = Vec::<(String, f64)>::new();
for (key, value) in map {
vec.push((key.to_string(), value))
};
vec
}
}

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

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

warning: enum `SensorMetric` is never used
  --> src/lib.rs:13:6
   |
13 | enum SensorMetric {
   |      ^^^^^^^^^^^^

warning: function `group_and_aggregate` is never used
  --> src/lib.rs:19:4
   |
19 | fn group_and_aggregate<O, E, D, K>(
   |    ^^^^^^^^^^^^^^^^^^^

warning: trait `Aggregator` is never used
  --> src/lib.rs:51:7
   |
51 | trait Aggregator {
   |       ^^^^^^^^^^

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

warning: struct `MetricAggregator` is never constructed
  --> src/lib.rs:81:8
   |
81 | 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:6:2
  |
5 | struct Event {
  |        ----- field in this struct
6 |     timestamp: u64,
  |     ^^^^^^^^^
  |
  = note: `Event` has a derived impl for the trait `Clone`, but this is intentionally ignored during dead code analysis
  = note: `#[warn(dead_code)]` on by default

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

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

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

Ясин качи първо решение на 12.11.2025 23:55 (преди 23 дена)