Решение на Домашно 1 - търсене на съкровища от Димитър Николов
Към профила на Димитър Николов
Резултати
- 16 точки от тестове
- 0 бонус точки
- 16 точки общо
- 4 успешни тест(а)
- 1 неуспешни тест(а)
Код
use std::collections::HashMap;
use std::sync::{
atomic::{AtomicBool, Ordering},
mpsc, Arc,
};
#[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,
}
pub struct Scan<'a> {
pub start_coord: usize,
pub cells: &'a [i32],
}
enum DroneMessage {
Treasure(TreasureLoc),
Done,
}
pub struct Drone {
lane_index: usize,
sender: mpsc::Sender<DroneMessage>,
should_stop_searching: Arc<AtomicBool>,
}
impl Drone {
pub fn explore(&mut self, scanner: &mut dyn Iterator<Item = Scan<'_>>) {
for scan in scanner {
if self.should_stop_searching.load(Ordering::Relaxed) {
break;
}
for (i, &value) in scan.cells.iter().enumerate() {
if value == 0 {
continue;
}
if value < 0 {
panic!("Values should not be negative");
}
let treasure = TreasureLoc {
lane_index: self.lane_index,
cell_coord: scan.start_coord + i,
value,
};
if self.sender.send(DroneMessage::Treasure(treasure)).is_err() {
self.done_or_panic();
return;
}
if self.should_stop_searching.load(Ordering::Relaxed) {
return;
}
}
}
self.done_or_panic();
}
fn done_or_panic(&mut self) {
if self.sender.send(DroneMessage::Done).is_err() {
panic!("Could not send message, indicating drone is done")
}
}
}
pub struct DroneController {
sender: mpsc::Sender<DroneMessage>,
receiver: mpsc::Receiver<DroneMessage>,
stop_searching_flag: Arc<AtomicBool>,
num_drones: usize,
}
const BIG_TREASURE_THRESHOLD: i32 = 999;
const SMALL_TREASURE_SUM_THRESHOLD: i32 = 300;
impl DroneController {
pub fn new() -> Self {
let (sender, receiver) = mpsc::channel();
DroneController {
sender,
receiver,
stop_searching_flag: Arc::new(AtomicBool::new(false)),
num_drones: 0,
}
}
pub fn create_drone(&mut self, lane_index: usize) -> Drone {
self.num_drones += 1;
Drone {
lane_index,
sender: self.sender.clone(),
should_stop_searching: Arc::clone(&self.stop_searching_flag),
}
}
pub fn run(&mut self) -> FoundTreasures {
let result = self.orchestrate_drones();
self.num_drones = 0;
result
}
fn orchestrate_drones(&mut self) -> FoundTreasures {
let mut best_small_treasure_per_lane: HashMap<usize, TreasureLoc> = HashMap::new();
while self.num_drones > 0 {
match self.receiver.recv() {
Ok(message) => {
let DroneMessage::Treasure(treasure) = message else {
self.num_drones -= 1;
continue;
};
if treasure.value >= BIG_TREASURE_THRESHOLD {
self.stop_searching_flag.store(true, Ordering::Relaxed);
return FoundTreasures::Big(treasure);
}
let current_value = treasure.value;
let best_treasure = best_small_treasure_per_lane
.entry(treasure.lane_index)
.and_modify(|current| {
if treasure.value > current.value {
*current = treasure.clone();
}
})
.or_insert(treasure);
if best_treasure.value != current_value {
continue;
}
if treasures_sum(&best_small_treasure_per_lane) >= SMALL_TREASURE_SUM_THRESHOLD
{
self.stop_searching_flag.store(true, Ordering::Relaxed);
return FoundTreasures::Small(
best_small_treasure_per_lane.into_values().collect(),
);
}
}
Err(_) => {
break;
}
}
}
if treasures_sum(&best_small_treasure_per_lane) >= SMALL_TREASURE_SUM_THRESHOLD {
FoundTreasures::Small(best_small_treasure_per_lane.into_values().collect())
} else {
FoundTreasures::Nothing
}
}
}
fn treasures_sum(treasure_per_lane: &HashMap<usize, TreasureLoc>) -> i32 {
treasure_per_lane.values().map(|t| t.value).sum()
}
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 unicode-ident v1.0.22
Compiling libc v0.2.178
Compiling quote v1.0.42
Compiling syn v2.0.111
Compiling futures-sink v0.3.31
Compiling futures-core v0.3.31
Compiling parking_lot_core v0.9.12
Compiling pin-project-lite v0.2.16
Compiling futures-channel v0.3.31
Compiling futures-task v0.3.31
Compiling cfg-if v1.0.4
Compiling pin-utils v0.1.0
Compiling futures-io v0.3.31
Compiling memchr v2.7.6
Compiling slab v0.4.11
Compiling scopeguard v1.2.0
Compiling smallvec v1.15.1
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 futures-macro v0.3.31
Compiling tokio-macros v2.6.0
Compiling mio v1.1.1
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-1pjg71b/solution)
warning: function `assert_send_static` is never used
--> src/lib.rs:173:10
|
173 | 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 18.12s
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 ... FAILED
failures:
---- solution_test::test_return_immediately_when_found stdout ----
thread '<unnamed>' panicked at src/lib.rs:75:13:
Could not send message, indicating drone is done
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread '<unnamed>' panicked at src/lib.rs:75:13:
Could not send message, indicating drone is done
thread '<unnamed>' panicked at tests/solution_test.rs:214:24:
called `Result::unwrap()` on an `Err` value: Any { .. }
failures:
solution_test::test_return_immediately_when_found
test result: FAILED. 4 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.10s
error: test failed, to rerun pass `--test solution_test`
