Решение на Домашно 1 - търсене на съкровища от Димитър Колев

Обратно към всички решения

Към профила на Димитър Колев

Резултати

  • 20 точки от тестове
  • 0 бонус точки
  • 20 точки общо
  • 5 успешни тест(а)
  • 0 неуспешни тест(а)

Код

use std::collections::HashMap;
use std::sync::{Arc, Condvar, Mutex};
#[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],
}
struct SharedState {
big_treasure: Option<TreasureLoc>,
small_treasures: HashMap<usize, TreasureLoc>,
small_total: i32,
done: bool,
active_drones: usize,
}
pub struct Drone {
lane_index: usize,
state: Arc<(Mutex<SharedState>, Condvar)>,
}
impl Drone {
pub fn explore(&mut self, scanner: &mut dyn Iterator<Item = Scan<'_>>) {
for scan in scanner {
let (lock, cvar) = &*self.state;
{
let state = lock.lock().unwrap();
if state.done {
return;
}
}
for (i, &value) in scan.cells.iter().enumerate() {
if value <= 0 {
continue;
}
let coord = scan.start_coord + i;
let treasure = TreasureLoc {
lane_index: self.lane_index,
cell_coord: coord,
value,
};
let mut state = lock.lock().unwrap();
if state.done {
return;
}
if value >= 999 {
state.big_treasure = Some(treasure);
state.done = true;
cvar.notify_all();
return;
} else {
let old_val = state
.small_treasures
.get(&self.lane_index)
.map_or(0, |t| t.value);
if value > old_val {
state.small_total += value - old_val;
state.small_treasures.insert(self.lane_index, treasure);
if state.small_total >= 300 {
state.done = true;
cvar.notify_all();
return;
}
}
}
}
}
let (lock, cvar) = &*self.state;
let mut state = lock.lock().unwrap();
state.active_drones -= 1;
if state.active_drones == 0 {
state.done = true;
cvar.notify_all();
}
}
}
pub struct DroneController {
state: Arc<(Mutex<SharedState>, Condvar)>,
}
impl DroneController {
pub fn new() -> Self {
let shared = SharedState {
big_treasure: None,
small_treasures: HashMap::new(),
small_total: 0,
done: false,
active_drones: 0,
};
DroneController {
state: Arc::new((Mutex::new(shared), Condvar::new())),
}
}
pub fn create_drone(&mut self, lane_index: usize) -> Drone {
let (lock, _) = &*self.state;
let mut state = lock.lock().unwrap();
state.active_drones += 1;
Drone {
lane_index,
state: Arc::clone(&self.state),
}
}
pub fn run(&mut self) -> FoundTreasures {
let (lock, cvar) = &*self.state;
let mut state = lock.lock().unwrap();
if state.active_drones == 0 {
return FoundTreasures::Nothing;
}
while !state.done {
state = cvar.wait(state).unwrap();
}
if let Some(big) = state.big_treasure.take() {
return FoundTreasures::Big(big);
}
if state.small_total >= 300 {
return FoundTreasures::Small(
std::mem::take(&mut state.small_treasures)
.into_values()
.collect(),
);
}
FoundTreasures::Nothing
}
}

Лог от изпълнението

Updating crates.io index
     Locking 46 packages to latest compatible versions
   Compiling proc-macro2 v1.0.104
   Compiling quote v1.0.42
   Compiling unicode-ident v1.0.22
   Compiling libc v0.2.178
   Compiling syn v2.0.111
   Compiling futures-core v0.3.31
   Compiling futures-sink v0.3.31
   Compiling pin-project-lite v0.2.16
   Compiling parking_lot_core v0.9.12
   Compiling futures-channel v0.3.31
   Compiling futures-io v0.3.31
   Compiling slab v0.4.11
   Compiling futures-task v0.3.31
   Compiling cfg-if v1.0.4
   Compiling pin-utils v0.1.0
   Compiling scopeguard v1.2.0
   Compiling memchr v2.7.6
   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 mio v1.1.1
   Compiling futures-macro v0.3.31
   Compiling tokio-macros v2.6.0
   Compiling futures-util v0.3.31
   Compiling socket2 v0.6.1
   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-1q2yyg2/solution)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 17.72s
     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

История (1 версия и 0 коментара)

Димитър качи първо решение на 21.12.2025 03:39 (преди около 1 месеца)