Решение на упр.04 задача 2 от Стилиян Иванов
Резултати
- 2 точки от тестове
- 0 бонус точки
- 2 точки общо
- 4 успешни тест(а)
- 0 неуспешни тест(а)
Код
use std::fmt::Debug;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompareResult {
Less,
Equal,
Greater,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortOrder {
Desc,
Asc,
}
pub trait Compare {
fn compare(&self, other: &Self) -> CompareResult;
}
pub trait Filter {
fn matches(&self, query: &str) -> bool;
}
pub trait Aggregate {
type Output;
fn aggregate(items: &[Self]) -> Self::Output
where
Self: Sized;
}
#[derive(Debug, Clone)]
pub struct Book {
pub title: String,
pub author: String,
pub year: u32,
pub rating: f32,
}
impl Filter for Book {
fn matches(&self, query: &str) -> bool {
self.title.contains(query) || self.author.contains(query)
}
}
impl Compare for Book {
fn compare(&self, other: &Self) -> CompareResult {
if self.year < other.year {
CompareResult::Less
} else if self.year > other.year {
CompareResult::Greater
} else {
CompareResult::Equal
}
}
}
impl Aggregate for Book {
type Output = f32;
fn aggregate(items: &[Self]) -> Self::Output {
if items.is_empty() {
return 0.0;
}
let sum: f32 = items.iter().map(|book| book.rating).sum();
sum / (items.len() as f32)
}
}
pub fn process_items<T>(items: Vec<T>, query: &str, order: SortOrder) -> (Vec<T>, T::Output)
where
T: Compare + Filter + Aggregate + Clone + Debug,
{
let mut filtered_items: Vec<T> = items
.into_iter()
.filter(|item| item.matches(query))
.collect();
let aggregated_value = T::aggregate(&filtered_items);
let n = filtered_items.len();
if n > 0 {
for i in 0..n {
let mut swapped = false;
for j in 0..(n - 1 - i) {
let comparison = filtered_items[j].compare(&filtered_items[j + 1]);
let should_swap = (order == SortOrder::Asc && comparison == CompareResult::Greater)
|| (order == SortOrder::Desc && comparison == CompareResult::Less);
if should_swap {
filtered_items.swap(j, j + 1);
swapped = true;
}
}
if !swapped {
break;
}
}
}
(filtered_items, aggregated_value)
}
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 unicode-ident v1.0.22
Compiling quote v1.0.41
Compiling futures-sink v0.3.31
Compiling futures-core v0.3.31
Compiling futures-channel v0.3.31
Compiling pin-project-lite v0.2.16
Compiling futures-task v0.3.31
Compiling syn v2.0.109
Compiling pin-utils v0.1.0
Compiling memchr v2.7.6
Compiling futures-io v0.3.31
Compiling slab v0.4.11
Compiling solution v0.1.0 (/tmp/d20251106-1757769-188w4aa/solution)
warning: function `main` is never used
--> src/lib.rs:105:4
|
105 | fn main() {
| ^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: `solution` (lib) generated 1 warning
Compiling futures-macro v0.3.31
Compiling futures-util v0.3.31
Compiling futures-executor v0.3.31
Compiling futures v0.3.31
warning: function `main` is never used
--> tests/../src/lib.rs:105:4
|
105 | fn main() {
| ^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: `solution` (test "solution_test") generated 1 warning
Finished `test` profile [unoptimized + debuginfo] target(s) in 8.57s
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
