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

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

Към профила на Йоан Грозев

Резултати

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

Код

use std::collections::HashMap;
use std::hash::Hash;
#[derive(Debug)]
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: impl Fn(&[D]) -> O,
) -> HashMap<K, O>
where
K: Eq + Hash,
{
let mut grouped: HashMap<K, Vec<D>> = HashMap::new();
for i in events
{
if let Some(data) = data_fn(i)
{
grouped.entry(group_fn(i)).or_insert_with(Vec::new).push(data);
}
}
let mut result = HashMap::new();
for (key, values) in grouped
{
let agg = aggregate(&values);
result.insert(key, agg);
}
result
}
pub trait Aggregator
{
type Output;
fn name(&self) -> String;
fn aggregate(&self, events: &[Event]) -> Vec<(String, Self::Output)>;
}
pub 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 result = group_and_aggregate(
events,
|ev| ev.metric,
|ev| Some(ev.value),
|values| values.iter().sum::<f64>() / values.len() as f64,
);
let mut out = Vec::new();
for (metric, avg) in result
{
out.push((format!("{:?}", metric), avg));
}
out
}
}
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 result = group_and_aggregate(
events,
|ev| ev.sensor.clone(),
|ev| {
if ev.metric == self.metric
{
Some(ev.value)
} else
{
None
}
},
|values| values.iter().sum::<f64>() / values.len() as f64,
);
let mut out = Vec::new();
for (sensor, avg) in result
{
out.push((sensor, avg));
}
out
}
}

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

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-sink v0.3.31
   Compiling futures-core v0.3.31
   Compiling futures-channel v0.3.31
   Compiling futures-task v0.3.31
   Compiling futures-io v0.3.31
   Compiling pin-utils v0.1.0
   Compiling syn v2.0.110
   Compiling memchr v2.7.6
   Compiling slab v0.4.11
   Compiling pin-project-lite v0.2.16
   Compiling solution v0.1.0 (/tmp/d20251113-1757769-1k4fctc/solution)
   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:7:9
  |
5 | pub struct Event 
  |            ----- field in this struct
6 | {
7 |     pub timestamp: u64,
  |         ^^^^^^^^^
  |
  = note: `Event` has a derived impl for the trait `Debug`, 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:52:8
   |
48 | pub trait Aggregator 
   |           ---------- method in this trait
...
52 |     fn name(&self) -> String;
   |        ^^^^

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

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

Йоан качи първо решение на 12.11.2025 11:38 (преди 24 дена)