Решение на Домашно 1 - търсене на съкровища от Милен Хаджиев
Резултати
- 20 точки от тестове
- 0 бонус точки
- 20 точки общо
- 5 успешни тест(а)
- 0 неуспешни тест(а)
Код
use std::collections::HashMap;
use std::sync::{Arc, mpsc};
use std::sync::atomic::{AtomicBool, Ordering};
#[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],
}
pub struct Drone {
lane_index: usize,
controller_tx: mpsc::Sender<(usize, Vec<TreasureLoc>)>,
stop_flag: Arc<AtomicBool>,
}
impl Drone {
pub fn new(lane_index: usize, controller_tx: mpsc::Sender<(usize, Vec<TreasureLoc>)>, stop_flag: Arc<AtomicBool>) -> Self {
Self {
lane_index,
controller_tx,
stop_flag,
}
}
pub fn explore(&mut self, scanner: &mut dyn Iterator<Item = Scan<'_>>) {
for scan in scanner {
if self.stop_flag.load(Ordering::Relaxed) {
break;
}
let mut treasures = Vec::new();
for (offset, &value) in scan.cells.iter().enumerate() {
if value > 0 {
let treasure = TreasureLoc {
lane_index: self.lane_index,
cell_coord: scan.start_coord + offset,
value,
};
treasures.push(treasure);
}
}
if !treasures.is_empty() {
let _ = self.controller_tx.send((self.lane_index, treasures));
}
if self.stop_flag.load(Ordering::Relaxed) {
break;
}
}
let _ = self.controller_tx.send((self.lane_index, Vec::new()));
}
}
pub struct DroneController {
treasure_receiver: mpsc::Receiver<(usize, Vec<TreasureLoc>)>,
controller_tx: mpsc::Sender<(usize, Vec<TreasureLoc>)>,
stop_flag: Arc<AtomicBool>,
drone_count: usize,
}
impl DroneController {
pub fn new() -> Self {
let (tx, rx) = mpsc::channel();
Self {
treasure_receiver: rx,
controller_tx: tx,
stop_flag: Arc::new(AtomicBool::new(false)),
drone_count: 0,
}
}
pub fn create_drone(&mut self, lane_index: usize) -> Drone {
self.drone_count += 1;
Drone::new(
lane_index,
self.controller_tx.clone(),
self.stop_flag.clone(),
)
}
pub fn run(&mut self) -> FoundTreasures {
let mut collected_treasures: HashMap<usize, Vec<TreasureLoc>> = HashMap::new();
let mut completed_drones = 0;
loop {
match self.treasure_receiver.recv() {
Ok((lane_index, new_treasures)) => {
if new_treasures.is_empty() {
completed_drones += 1;
if completed_drones >= self.drone_count && !self.stop_flag.load(Ordering::Relaxed) {
return FoundTreasures::Nothing;
}
continue;
}
collected_treasures.insert(lane_index, new_treasures.clone());
let result = Self::check_solution(&collected_treasures);
if let FoundTreasures::Nothing = result {
continue;
} else {
self.stop_flag.store(true, Ordering::Relaxed);
return result;
}
}
Err(_) => {
break;
}
}
}
FoundTreasures::Nothing
}
fn check_solution(treasures_map: &HashMap<usize, Vec<TreasureLoc>>) -> FoundTreasures {
for (_, treasures) in treasures_map.iter() {
for treasure in treasures {
if treasure.value >= 999 {
return FoundTreasures::Big(treasure.clone());
}
}
}
let mut best_treasures = Vec::new();
for (_, treasures) in treasures_map.iter() {
if let Some(best) = treasures.iter().max_by_key(|t| t.value) {
best_treasures.push(best.clone());
}
}
best_treasures.sort_by(|a, b| b.value.cmp(&a.value));
let mut selected = Vec::new();
let mut total = 0;
for treasure in best_treasures {
if treasure.value < 999 {
selected.push(treasure.clone());
total += treasure.value;
if total >= 300 {
return FoundTreasures::Small(selected);
}
}
}
FoundTreasures::Nothing
}
}
unsafe impl Send for Drone {}
unsafe impl Send for DroneController {}
unsafe impl<'a> Send for Scan<'a> {}
Лог от изпълнението
Updating crates.io index
Locking 46 packages to latest compatible versions
Compiling proc-macro2 v1.0.104
Compiling quote v1.0.42
Compiling libc v0.2.178
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 parking_lot_core v0.9.12
Compiling futures-sink v0.3.31
Compiling futures-channel v0.3.31
Compiling futures-io v0.3.31
Compiling memchr v2.7.6
Compiling pin-utils v0.1.0
Compiling futures-task v0.3.31
Compiling slab v0.4.11
Compiling scopeguard v1.2.0
Compiling smallvec v1.15.1
Compiling cfg-if v1.0.4
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 mio v1.1.1
Compiling socket2 v0.6.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-552bmp/solution)
Finished `test` profile [unoptimized + debuginfo] target(s) in 17.96s
Running tests/solution_test.rs (target/debug/deps/solution_test-f512224d9fb3caf8)
running 5 tests
test solution_test::test_big_treasure ... ok
test solution_test::test_nothing ... 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
