Решение на упр.10 задача 1 от Йосиф Хамед
Резултати
- 2 точки от тестове
- 0 бонус точки
- 2 точки общо
- 2 успешни тест(а)
- 0 неуспешни тест(а)
Код
use std::{
sync::{Arc, Mutex},
thread,
};
#[derive(Clone, Copy)]
pub enum Predicate {
GreaterThan100,
Even,
Prime,
DivisibleBy7,
}
fn prediacte_filter(p: Predicate, n: i32) -> bool {
let is_prime = |n: i32| -> bool {
if n < 2 {
return false;
}
let limit = (n as f64).sqrt() as i32;
for i in 2..=limit {
if n % i == 0 {
return false;
}
}
true
};
match p {
Predicate::GreaterThan100 => n > 100,
Predicate::Even => n % 2 == 0,
Predicate::Prime => is_prime(n),
Predicate::DivisibleBy7 => n % 7 == 0,
}
}
#[derive(Debug)]
struct Res {
i: usize,
v: Vec<i32>,
}
pub fn parallel_filter(data: Vec<i32>, n_threads: usize, predicate: Predicate) -> Vec<i32> {
let data = Arc::new(data);
let result = Arc::new(Mutex::new(Vec::new()));
let chunk_size = (data.len() + n_threads - 1) / n_threads;
let mut handles = Vec::new();
for i in 0..n_threads {
let data = Arc::clone(&data);
let result = Arc::clone(&result);
let start = i * chunk_size;
let end = ((i + 1) * chunk_size).min(data.len());
handles.push(thread::spawn(move || {
let filtered: Vec<i32> = data[start..end]
.iter()
.cloned()
.filter(|&n| prediacte_filter(predicate, n))
.collect();
let r = Res { i: i, v: filtered };
result.lock().unwrap().push(r);
}));
}
for h in handles {
h.join().unwrap();
}
let mut r = Arc::try_unwrap(result).unwrap().into_inner().unwrap();
r.sort_by(|a, b| a.i.cmp(&b.i));
r.iter().flat_map(|r| r.v.clone()).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-sink v0.3.31
Compiling futures-core v0.3.31
Compiling futures-channel v0.3.31
Compiling slab v0.4.11
Compiling syn v2.0.111
Compiling futures-task v0.3.31
Compiling memchr v2.7.6
Compiling futures-io v0.3.31
Compiling pin-utils v0.1.0
Compiling pin-project-lite v0.2.16
Compiling solution v0.1.0 (/tmp/d20251218-1757769-169x7b5/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.80s
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
