Решение на упр.05 задача 2 от Милен Хаджиев
Резултати
- 0 точки от тестове
- 0 бонус точки
- 0 точки общо
- 0 успешни тест(а)
- 0 неуспешни тест(а)
Код
use std::collections::HashMap;
use std::hash::Hash;
#[derive(Debug, 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 intermediate: HashMap<K, Vec<D>> = HashMap::new();
for ev in events {
if let Some(data) = data_fn(ev) {
let key = group_fn(ev);
intermediate.entry(key).or_default().push(data);
}
}
let mut result: HashMap<K, O> = HashMap::new();
for (k, values) in intermediate {
let out = aggregate(&values);
result.insert(k, out);
}
result
}
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: HashMap<SensorMetric, f64> = group_and_aggregate(
events,
|e| e.metric,
|e| Some(e.value),
|vals: &[f64]| {
if vals.is_empty() {
0.0
} else {
let sum: f64 = vals.iter().copied().sum();
sum / (vals.len() as f64)
}
},
);
let order = [
SensorMetric::Load,
SensorMetric::Frequency,
SensorMetric::Temperature,
];
let mut out = Vec::with_capacity(order.len());
for m in order.iter() {
let avg = *map.get(m).unwrap_or(&0.0);
out.push((format!("{:?}", m), avg));
}
out
}
}
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| e.sensor.clone(),
|e| if e.metric == self.metric { Some(e.value) } else { None },
|vals: &[f64]| {
if vals.is_empty() {
0.0
} else {
let sum: f64 = vals.iter().copied().sum();
sum / (vals.len() as f64)
}
},
);
map.into_iter().collect()
}
}
#[derive(Debug)]
struct FloatApprox(f64);
impl PartialEq<FloatApprox> for FloatApprox {
fn eq(&self, rhs: &FloatApprox) -> bool {
return self.0.signum() == rhs.0.signum() &&
(self.0 - rhs.0).abs() < 0.01;
}
}
Лог от изпълнението
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-utils v0.1.0
Compiling slab v0.4.11
Compiling syn v2.0.110
Compiling futures-io v0.3.31
Compiling futures-task v0.3.31
Compiling memchr v2.7.6
Compiling pin-project-lite v0.2.16
Compiling solution v0.1.0 (/tmp/d20251113-1757769-1vy6v8g/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:46:7
|
46 | trait Aggregator {
| ^^^^^^^^^^
warning: struct `TotalAggregator` is never constructed
--> src/lib.rs:53:8
|
53 | struct TotalAggregator;
| ^^^^^^^^^^^^^^^
warning: struct `MetricAggregator` is never constructed
--> src/lib.rs:91:8
|
91 | struct MetricAggregator {
| ^^^^^^^^^^^^^^^^
warning: struct `FloatApprox` is never constructed
--> src/lib.rs:122:8
|
122 | struct FloatApprox(f64);
| ^^^^^^^^^^^
warning: `solution` (lib) generated 7 warnings
Compiling futures-macro v0.3.31
Compiling futures-util v0.3.31
Compiling futures-executor v0.3.31
Compiling futures v0.3.31
error[E0428]: the name `FloatApprox` is defined multiple times
--> tests/../src/lib.rs:122:1
|
122 | struct FloatApprox(f64);
| ^^^^^^^^^^^^^^^^^^^^^^^^ `FloatApprox` redefined here
|
::: tests/solution_test.rs:9:1
|
9 | struct FloatApprox(f64);
| ------------------------ previous definition of the type `FloatApprox` here
|
= note: `FloatApprox` must be defined only once in the type namespace of this module
error[E0119]: conflicting implementations of trait `Debug` for type `solution_test::FloatApprox`
--> tests/solution_test.rs:8:10
|
8 | #[derive(Debug)]
| ^^^^^ conflicting implementation for `solution_test::FloatApprox`
|
::: tests/../src/lib.rs:121:10
|
121 | #[derive(Debug)]
| ----- first implementation here
|
= note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0119]: conflicting implementations of trait `PartialEq` for type `solution_test::FloatApprox`
--> tests/../src/lib.rs:123:1
|
123 | impl PartialEq<FloatApprox> for FloatApprox {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `solution_test::FloatApprox`
|
::: tests/solution_test.rs:10:1
|
10 | impl PartialEq<FloatApprox> for FloatApprox {
| ------------------------------------------- first implementation here
Some errors have detailed explanations: E0119, E0428.
For more information about an error, try `rustc --explain E0119`.
error: could not compile `solution` (test "solution_test") due to 3 previous errors
