Решение на упр.04 задача 2 от Йоанна Ненкова
Резултати
- 2 точки от тестове
- 0 бонус точки
- 2 точки общо
- 4 успешни тест(а)
- 0 неуспешни тест(а)
Код
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SortOrder {
Desc,
Asc,
}
#[derive(Clone)]
struct Book {
title: String,
author: String,
year: u32,
rating: f32,
}
impl Book {
fn new(title: String, author: String, year: u32, rating: f32) -> Self {
Book {title, author, year, rating}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CompareResult {
Less,
Equal,
Greater,
}
trait Compare {
fn compare(&self, other: &Self) -> CompareResult;
}
impl Compare for Book {
fn compare(&self, other: &Self) -> CompareResult {
if self.year > other.year { CompareResult::Greater }
else if self.year == other.year { CompareResult::Equal }
else { CompareResult::Less }
}
}
trait Filter {
fn matches(&self, query: &str) -> bool;
}
impl Filter for Book {
fn matches(&self, query: &str) -> bool {
if self.title.contains(query) || self.author.contains(query) { true }
else { false }
}
}
trait Aggregate {
type Output;
fn aggregate(items: &[Self]) -> Self::Output
where
Self: Sized;
}
impl Aggregate for Book {
type Output = f32;
fn aggregate(items: &[Self]) -> Self::Output
where
Self: Sized {
if items.is_empty() {
return f32::NAN;
}
let mut sum: f32 = 0.0;
for i in items.iter() {
sum += i.rating;
}
return sum / items.len() as f32;
}
}
fn process_items<T>(items: Vec<T>, query: &str, order: SortOrder) -> (Vec<T>, T::Output)
where
T: Compare + Filter + Aggregate + Clone,
{
let mut filtered = Vec::<T>::new();
for i in items.iter() {
if i.matches(query) { filtered.push(i.clone()) };
}
let n = filtered.len();
for i in 0..n {
for j in 0..n - 1 - i {
let cmp = filtered[j].compare(&filtered[j + 1]);
let should_swap = match order {
SortOrder::Asc => cmp == CompareResult::Greater,
SortOrder::Desc => cmp == CompareResult::Less,
};
if should_swap {
filtered.swap(j, j + 1);
}
}
}
let agg = T::aggregate(&filtered);
(filtered, agg)
}
fn main() {
let books = vec![
Book { title: "The Rust Book".into(), author: "Steve".into(), year: 2018, rating: 4.7 },
Book { title: "Rust Patterns".into(), author: "Anna".into(), year: 2020, rating: 4.9 },
Book { title: "C Programming".into(), author: "Dennis".into(), year: 1978, rating: 4.3 },
];
let (result, avg_rating) = process_items(books, "Rust", SortOrder::Asc);
println!("Filtered & sorted:");
for b in &result {
println!("{} by {} ({})", b.title, b.author, b.year);
}
println!("Average rating: {:.2}", avg_rating);
}
Лог от изпълнението
Updating crates.io index
Locking 17 packages to latest compatible versions
Compiling proc-macro2 v1.0.103
Compiling quote v1.0.41
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-task v0.3.31
Compiling slab v0.4.11
Compiling pin-utils v0.1.0
Compiling syn v2.0.109
Compiling memchr v2.7.6
Compiling pin-project-lite v0.2.16
Compiling futures-io v0.3.31
Compiling solution v0.1.0 (/tmp/d20251106-1757769-1jycedc/solution)
warning: enum `SortOrder` is never used
--> src/lib.rs:2:6
|
2 | enum SortOrder {
| ^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: struct `Book` is never constructed
--> src/lib.rs:8:8
|
8 | struct Book {
| ^^^^
warning: associated function `new` is never used
--> src/lib.rs:16:8
|
15 | impl Book {
| --------- associated function in this implementation
16 | fn new(title: String, author: String, year: u32, rating: f32) -> Self {
| ^^^
warning: enum `CompareResult` is never used
--> src/lib.rs:22:6
|
22 | enum CompareResult {
| ^^^^^^^^^^^^^
warning: trait `Compare` is never used
--> src/lib.rs:28:7
|
28 | trait Compare {
| ^^^^^^^
warning: trait `Filter` is never used
--> src/lib.rs:40:7
|
40 | trait Filter {
| ^^^^^^
warning: trait `Aggregate` is never used
--> src/lib.rs:51:7
|
51 | trait Aggregate {
| ^^^^^^^^^
warning: function `process_items` is never used
--> src/lib.rs:75:4
|
75 | fn process_items<T>(items: Vec<T>, query: &str, order: SortOrder) -> (Vec<T>, T::Output)
| ^^^^^^^^^^^^^
warning: function `main` is never used
--> src/lib.rs:103:4
|
103 | fn main() {
| ^^^^
warning: `solution` (lib) generated 9 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: variant `Asc` is never constructed
--> tests/../src/lib.rs:4:3
|
2 | enum SortOrder {
| --------- variant in this enum
3 | Desc,
4 | Asc,
| ^^^
|
= note: `SortOrder` has derived impls for the traits `Clone` and `Debug`, but these are intentionally ignored during dead code analysis
= note: `#[warn(dead_code)]` on by default
warning: associated function `new` is never used
--> tests/../src/lib.rs:16:8
|
15 | impl Book {
| --------- associated function in this implementation
16 | fn new(title: String, author: String, year: u32, rating: f32) -> Self {
| ^^^
warning: function `main` is never used
--> tests/../src/lib.rs:103:4
|
103 | fn main() {
| ^^^^
warning: `solution` (test "solution_test") generated 3 warnings
Finished `test` profile [unoptimized + debuginfo] target(s) in 8.73s
Running tests/solution_test.rs (target/debug/deps/solution_test-8c2c5f784503f204)
running 4 tests
test solution_test::test_aggregate ... ok
test solution_test::test_compare ... ok
test solution_test::test_matches ... ok
test solution_test::test_process ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
