Решение на Домашно 1 - търсене на съкровища от Венислав Трендафилов
Към профила на Венислав Трендафилов
Резултати
- 20 точки от тестове
- 0 бонус точки
- 20 точки общо
- 5 успешни тест(а)
- 0 неуспешни тест(а)
Код
use std::sync::{mpsc, Arc, Mutex};
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TreasureLoc {
pub lane_index: usize,
pub cell_coord: usize,
pub value: i32,
}
#[derive(Debug, PartialEq, Eq)]
pub enum FoundTreasures {
Big(TreasureLoc),
Small(Vec<TreasureLoc>),
Nothing,
}
enum Message {
Found(TreasureLoc),
}
pub struct Scan<'a> {
// coord of first element in `cells`
pub start_coord: usize,
pub cells: &'a [i32],
}
pub struct Drone {
lane_index: usize,
sender: mpsc::Sender<Message>,
finished: Arc<Mutex<bool>>,
}
impl Drone {
pub fn explore(&mut self, scanner: &mut dyn Iterator<Item = Scan<'_>>) {
for scan in scanner {
if *self.finished.lock().unwrap() {
return;
}
for (i, &val) in scan.cells.iter().enumerate() {
if val <= 0 {
continue;
}
let tr_loc = TreasureLoc {
lane_index: self.lane_index,
cell_coord: scan.start_coord + i,
value: val,
};
if self.sender.send(Message::Found(tr_loc)).is_err() {
return;
}
if *self.finished.lock().unwrap() {
return;
}
}
}
}
}
pub struct DroneController {
sender: Option<mpsc::Sender<Message>>,
receiver: mpsc::Receiver<Message>,
finished: Arc<Mutex<bool>>,
}
impl DroneController {
pub fn new() -> Self {
let (sender, receiver) = mpsc::channel();
Self {
sender: Some(sender),
receiver,
finished: Arc::new(Mutex::new(false)),
}
}
pub fn create_drone(&mut self, lane_index: usize) -> Drone {
Drone {
lane_index,
sender: self.sender.as_ref().unwrap().clone(),
finished: Arc::clone(&self.finished),
}
}
pub fn run(&mut self) -> FoundTreasures {
let mut best_per_lane: HashMap<usize, TreasureLoc> = HashMap::new();
let mut total_value = 0;
self.sender.take();
while let Ok(msg) = self.receiver.recv() {
match msg {
Message::Found(loc) => {
if loc.value >= 999 {
*self.finished.lock().unwrap() = true;
return FoundTreasures::Big(loc);
}
let curr = best_per_lane.entry(loc.lane_index).or_insert(TreasureLoc {
lane_index: loc.lane_index,
cell_coord: 0,
value: 0,
});
if loc.value > curr.value {
total_value -= curr.value;
total_value += loc.value;
*curr = loc;
}
if total_value >= 300 {
*self.finished.lock().unwrap() = true;
let collected_smalls: Vec<TreasureLoc> = best_per_lane.into_values().collect();
return FoundTreasures::Small(collected_smalls);
}
}
}
}
if total_value >= 300 {
let collected_smalls: Vec<TreasureLoc> = best_per_lane.into_values().collect();
FoundTreasures::Small(collected_smalls)
} else {
FoundTreasures::Nothing
}
}
}
const fn assert_send_static<T: Send + 'static>() {}
const _: () = assert_send_static::<DroneController>();
const _: () = assert_send_static::<Drone>();
Лог от изпълнението
Updating crates.io index
Locking 46 packages to latest compatible versions
Compiling proc-macro2 v1.0.104
Compiling libc v0.2.178
Compiling quote v1.0.42
Compiling unicode-ident v1.0.22
Compiling syn v2.0.111
Compiling futures-core v0.3.31
Compiling pin-project-lite v0.2.16
Compiling futures-sink v0.3.31
Compiling parking_lot_core v0.9.12
Compiling futures-channel v0.3.31
Compiling cfg-if v1.0.4
Compiling futures-task v0.3.31
Compiling memchr v2.7.6
Compiling smallvec v1.15.1
Compiling slab v0.4.11
Compiling futures-io v0.3.31
Compiling pin-utils v0.1.0
Compiling scopeguard v1.2.0
Compiling lock_api v0.4.14
Compiling errno v0.3.14
Compiling signal-hook-registry v1.4.8
Compiling parking_lot v0.12.5
Compiling socket2 v0.6.1
Compiling mio v1.1.1
Compiling futures-macro v0.3.31
Compiling tokio-macros v2.6.0
Compiling futures-util v0.3.31
Compiling bytes v1.11.0
Compiling tokio v1.48.0
Compiling futures-executor v0.3.31
Compiling futures v0.3.31
Compiling solution v0.1.0 (/tmp/d20251229-4108951-1mkb4kn/solution)
warning: function `assert_send_static` is never used
--> src/lib.rs:132:10
|
132 | const fn assert_send_static<T: Send + 'static>() {}
| ^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: `solution` (lib) generated 1 warning
Finished `test` profile [unoptimized + debuginfo] target(s) in 17.67s
Running tests/solution_test.rs (target/debug/deps/solution_test-f512224d9fb3caf8)
running 5 tests
test solution_test::test_nothing ... ok
test solution_test::test_big_treasure ... ok
test solution_test::test_small_treasure ... ok
test solution_test::test_small_treasure_2 ... ok
test solution_test::test_return_immediately_when_found ... ok
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.10s
