Решение на упр.05 задача 2 от Мариян Момчилов

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

Към профила на Мариян Момчилов

Резултати

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

Код

use std::{collections::HashMap, hash::Hash};
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 hm = HashMap::<K, Vec<D>>::new();
for event in events {
match data_fn(event) {
Some(data) => {
let group = group_fn(event);
if !hm.contains_key(&group) {
hm.insert(group, Vec::new());
}
let group: K = group_fn(event);
let group_vec = hm.get_mut(&group).unwrap();
group_vec.push(data);
}
None => {}
}
}
let mut result = HashMap::<K, O>::new();
for (k, v) in hm {
result.insert(k, aggregate(&v));
}
result
}
trait Aggregator {
type Output;
fn name(&self) -> String;
fn aggregate(&self, events: &[Event]) -> Vec<(String, Self::Output)>;
}
impl SensorMetric {
fn name(&self) -> String {
match *self {
Self::Frequency => String::from("Frequency"),
Self::Load => String::from("Load"),
Self::Temperature => String::from("Temperature"),
}
}
}
impl Event {
fn value(&self) -> Option<f64> {
Some(self.value)
}
fn name(&self) -> String {
SensorMetric::name(&self.metric)
}
fn avg(events: &[f64]) -> f64 {
let mut s = 0.0;
for event in events {
s += *event;
}
s / events.len() as f64
}
}
// Имплементирайте агрегация, която връща средната стойност на метриките, групирани по тип.
// Резултата трябва да е вектор от три елемента:
// - ("Load", <средната стойност на Load метриките от всички сензори>)
// - ("Frequency", <средната стойност на Frequency метриките от всички сензори>)
// - ("Temperature", <средната стойност на Temperature метриките от всички сензори>)
struct TotalAggregator {}
impl TotalAggregator {
fn event_value(event: &Event) -> Option<f64> {
Some(event.value)
}
fn event_name(event: &Event) -> String {
SensorMetric::name(&event.metric)
}
fn event_avg(events: &[f64]) -> f64 {
let mut s = 0.0;
for event in events {
s += *event;
}
s / (events.len() as f64)
}
}
impl Aggregator for TotalAggregator {
type Output = f64;
fn name(&self) -> String {
"total".to_string()
}
fn aggregate(&self, events: &[Event]) -> Vec<(String, f64)> {
group_and_aggregate(
events,
TotalAggregator::event_name,
TotalAggregator::event_value,
TotalAggregator::event_avg,
)
.into_iter()
.collect()
}
}
// Имплементирайте агрегация, която по даден тип на метрика, връща сумата от метриките
// от този тип, групирани по сензор.
// Пример при `MetricAggreator { metric: SensorMetric::Load }`, може да върне:
// - ("cpu0", <средната стойност от Load метиките за сензор cpu0>)
// - ("cpu1", <средната стойност от Load метиките за сензор cpu1>)
// - ("gpu0", <средната стойност от Load метиките за сензор gpu0>)
struct MetricAggregator {
metric: SensorMetric,
}
impl MetricAggregator {
fn load_value(event: &Event) -> Option<f64> {
if event.metric == SensorMetric::Load {
return Some(event.value);
}
None
}
fn temp_value(event: &Event) -> Option<f64> {
if event.metric == SensorMetric::Temperature {
return Some(event.value);
}
None
}
fn frequency_value(event: &Event) -> Option<f64> {
if event.metric == SensorMetric::Frequency {
return Some(event.value);
}
None
}
fn event_name(event: &Event) -> String {
event.sensor.clone()
}
fn event_avg(events: &[f64]) -> f64 {
let mut s = 0.0;
for event in events {
s += *event;
}
s / (events.len() as f64)
}
}
impl Aggregator for MetricAggregator {
type Output = f64;
fn name(&self) -> String {
format!("{:?}", self.metric)
}
fn aggregate(&self, events: &[Event]) -> Vec<(String, f64)> {
group_and_aggregate(
events,
MetricAggregator::event_name,
match self.metric {
SensorMetric::Frequency => MetricAggregator::frequency_value,
SensorMetric::Load => MetricAggregator::load_value,
SensorMetric::Temperature => MetricAggregator::temp_value,
},
MetricAggregator::event_avg,
)
.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);
}
}
// total "Temperature": 38.18
// total "Load": 4.82
// total "Frequency": 2166.67
// Load "gpu0": 13.45
// Load "cpu1": 0.04
// Load "cpu0": 0.98
// Temperature "cpu1": 33.33
// Temperature "cpu0": 56.20
// Temperature "gpu0": 25.00
}

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

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

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

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

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

warning: method `name` is never used
  --> src/lib.rs:56:8
   |
55 | impl SensorMetric {
   | ----------------- method in this implementation
56 |     fn name(&self) -> String {
   |        ^^^^

warning: associated items `value`, `name`, and `avg` are never used
  --> src/lib.rs:66:8
   |
65 | impl Event {
   | ---------- associated items in this implementation
66 |     fn value(&self) -> Option<f64> {
   |        ^^^^^
...
70 |     fn name(&self) -> String {
   |        ^^^^
...
74 |     fn avg(events: &[f64]) -> f64 {
   |        ^^^

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

warning: associated functions `event_value`, `event_name`, and `event_avg` are never used
  --> src/lib.rs:90:8
   |
89 | impl TotalAggregator {
   | -------------------- associated functions in this implementation
90 |     fn event_value(event: &Event) -> Option<f64> {
   |        ^^^^^^^^^^^
...
94 |     fn event_name(event: &Event) -> String {
   |        ^^^^^^^^^^
...
98 |     fn event_avg(events: &[f64]) -> f64 {
   |        ^^^^^^^^^

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

warning: associated functions `load_value`, `temp_value`, `frequency_value`, `event_name`, and `event_avg` are never used
   --> src/lib.rs:136:8
    |
135 | impl MetricAggregator {
    | --------------------- associated functions in this implementation
136 |     fn load_value(event: &Event) -> Option<f64> {
    |        ^^^^^^^^^^
...
143 |     fn temp_value(event: &Event) -> Option<f64> {
    |        ^^^^^^^^^^
...
150 |     fn frequency_value(event: &Event) -> Option<f64> {
    |        ^^^^^^^^^^^^^^^
...
157 |     fn event_name(event: &Event) -> String {
    |        ^^^^^^^^^^
...
161 |     fn event_avg(events: &[f64]) -> f64 {
    |        ^^^^^^^^^

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

warning: `solution` (lib) generated 11 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:4:5
  |
3 | struct Event {
  |        ----- field in this struct
4 |     timestamp: u64,
  |     ^^^^^^^^^
  |
  = note: `#[warn(dead_code)]` on by default

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

warning: associated items `value`, `name`, and `avg` are never used
  --> tests/../src/lib.rs:66:8
   |
65 | impl Event {
   | ---------- associated items in this implementation
66 |     fn value(&self) -> Option<f64> {
   |        ^^^^^
...
70 |     fn name(&self) -> String {
   |        ^^^^
...
74 |     fn avg(events: &[f64]) -> f64 {
   |        ^^^

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

warning: `solution` (test "solution_test") generated 4 warnings
    Finished `test` profile [unoptimized + debuginfo] target(s) in 8.94s
     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 коментара)

Мариян качи първо решение на 10.11.2025 22:59 (преди 25 дена)