Решение на упр.05 задача 2 от Виктор Карталов

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

Към профила на Виктор Карталов

Резултати

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

Код

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 buckets: HashMap<K, Vec<D>> = HashMap::new();
for e in events {
if let Some(d) = data_fn(e) {
let key = group_fn(e);
buckets.entry(key).or_insert_with(Vec::new).push(d);
}
}
let mut out: HashMap<K, O> = HashMap::with_capacity(buckets.len());
for (k, vec_d) in buckets {
let res = aggregate(&vec_d);
out.insert(k, res);
}
out
}
trait Aggregator {
type Output;
fn name(&self) -> String;
fn aggregate(&self, events: &[Event]) -> Vec<(String, Self::Output)>;
}
fn mean(xs: &[f64]) -> f64 {
if xs.is_empty() {
0.0
} else {
let sum: f64 = xs.iter().sum();
sum / (xs.len() as f64)
}
}
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: HashMap<SensorMetric, f64> = group_and_aggregate(
events,
|e: &Event| e.metric,
|e: &Event| Some(e.value),
|vals: &[f64]| mean(vals),
);
vec![
("Load".to_string(), *map.get(&SensorMetric::Load).unwrap_or(&0.0)),
(
"Frequency".to_string(),
*map.get(&SensorMetric::Frequency).unwrap_or(&0.0),
),
(
"Temperature".to_string(),
*map.get(&SensorMetric::Temperature).unwrap_or(&0.0),
),
]
}
}
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 map: HashMap<String, f64> = group_and_aggregate(
events,
|e: &Event| e.sensor.clone(), // ключ: собствен string на сензора
|e: &Event| {
if e.metric == self.metric {
Some(e.value)
} else {
None
}
},
|vals: &[f64]| mean(vals),
);
map.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);
}
}
}

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

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-io v0.3.31
   Compiling futures-task 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-quzppz/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:44:7
   |
44 | trait Aggregator {
   |       ^^^^^^^^^^

warning: function `mean` is never used
  --> src/lib.rs:50:4
   |
50 | fn mean(xs: &[f64]) -> f64 {
   |    ^^^^

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

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

warning: function `main` is never used
   --> src/lib.rs:116:4
    |
116 | fn main() {
    |    ^^^^

warning: `solution` (lib) generated 8 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:47:8
   |
44 | trait Aggregator {
   |       ---------- method in this trait
...
47 |     fn name(&self) -> String;
   |        ^^^^

warning: function `main` is never used
   --> tests/../src/lib.rs:116:4
    |
116 | fn main() {
    |    ^^^^

warning: `solution` (test "solution_test") generated 3 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_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 19:02 (преди 24 дена)