Решение на упр.10 задача 1 от Стилиян Иванов
Резултати
- 2 точки от тестове
- 0 бонус точки
- 2 точки общо
- 2 успешни тест(а)
- 0 неуспешни тест(а)
Код
use std::thread;
#[derive(Clone, Copy)]
pub enum Predicate {
GreaterThan100,
Even,
Prime,
DivisibleBy7,
}
fn is_prime(n: i32) -> bool {
const PRIMES: &[i32] = &[
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107,
109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359,
367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491,
499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641,
643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787,
797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997,
];
PRIMES.contains(&n)
}
pub fn parallel_filter(data: Vec<i32>, n_threads: usize, predicate: Predicate) -> Vec<i32> {
if n_threads == 0 || data.is_empty() {
return Vec::new();
}
let chunk_size = (data.len() + n_threads - 1) / n_threads;
let chunks: Vec<Vec<i32>> = data.chunks(chunk_size).map(|c| c.to_vec()).collect();
let mut handles = Vec::with_capacity(chunks.len());
for chunk in chunks {
let handle = thread::spawn(move || {
chunk.into_iter().filter(|&x| {
match predicate {
Predicate::GreaterThan100 => x > 100,
Predicate::Even => x % 2 == 0,
Predicate::Prime => is_prime(x),
Predicate::DivisibleBy7 => x % 7 == 0,
}
}).collect::<Vec<_>>()
});
handles.push(handle);
}
let mut result = Vec::with_capacity(data.len());
for handle in handles {
result.extend(handle.join().unwrap());
}
result
}
Лог от изпълнението
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-sink v0.3.31
Compiling futures-core 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 slab v0.4.11
Compiling pin-project-lite v0.2.16
Compiling memchr v2.7.6
Compiling futures-task v0.3.31
Compiling solution v0.1.0 (/tmp/d20251218-1757769-azfsdf/solution)
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.64s
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.00s
