Решение на упр.10 задача 1 от Димитър Николов
Към профила на Димитър Николов
Резултати
- 2 точки от тестове
- 0 бонус точки
- 2 точки общо
- 2 успешни тест(а)
- 0 неуспешни тест(а)
Код
use std::thread;
#[derive(Clone)]
enum Predicate {
GreaterThan100,
Even,
Prime,
DivisibleBy7,
}
fn is_prime(val: i32) -> bool {
for n in 2..=val.isqrt() {
if val % n == 0 {
return false;
}
}
true
}
impl Predicate {
fn matches(&self, val: i32) -> bool {
match self {
Predicate::GreaterThan100 => val > 100,
Predicate::Even => val % 2 == 0,
Predicate::Prime => is_prime(val),
Predicate::DivisibleBy7 => val % 7 == 0,
}
}
}
fn filter(data: Vec<i32>, predicate: Predicate) -> Vec<i32> {
data.into_iter()
.filter(|val| predicate.matches(*val))
.collect()
}
fn parallel_filter(data: Vec<i32>, n_threads: usize, predicate: Predicate) -> Vec<i32> {
let handlers: Vec<thread::JoinHandle<Vec<i32>>> = data
.chunks(n_threads)
.map(|chunk| Vec::from(chunk))
.map(|vec| {
let predicate = predicate.clone();
thread::spawn(move || filter(vec, predicate))
})
.collect();
handlers
.into_iter()
.filter_map(|handle| handle.join().ok())
.flatten()
.collect()
}
Лог от изпълнението
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 futures-io v0.3.31
Compiling syn v2.0.111
Compiling pin-project-lite v0.2.16
Compiling slab v0.4.11
Compiling futures-task v0.3.31
Compiling memchr v2.7.6
Compiling solution v0.1.0 (/tmp/d20251218-1757769-vo1ksj/solution)
warning: enum `Predicate` is never used
--> src/lib.rs:4:6
|
4 | enum Predicate {
| ^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: function `is_prime` is never used
--> src/lib.rs:11:4
|
11 | fn is_prime(val: i32) -> bool {
| ^^^^^^^^
warning: method `matches` is never used
--> src/lib.rs:21:8
|
20 | impl Predicate {
| -------------- method in this implementation
21 | fn matches(&self, val: i32) -> bool {
| ^^^^^^^
warning: function `filter` is never used
--> src/lib.rs:31:4
|
31 | fn filter(data: Vec<i32>, predicate: Predicate) -> Vec<i32> {
| ^^^^^^
warning: function `parallel_filter` is never used
--> src/lib.rs:37:4
|
37 | fn parallel_filter(data: Vec<i32>, n_threads: usize, predicate: Predicate) -> Vec<i32> {
| ^^^^^^^^^^^^^^^
warning: `solution` (lib) generated 5 warnings
Compiling futures-macro v0.3.31
Compiling futures-util v0.3.31
Compiling futures-executor v0.3.31
Compiling futures v0.3.31
Finished `test` profile [unoptimized + debuginfo] target(s) in 8.55s
Running tests/solution_test.rs (target/debug/deps/solution_test-ee0783488e12dce9)
running 2 tests
test solution_test::test_basic ... ok
test solution_test::test_uneven_split ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
