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

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

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

Резултати

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

Код

use std::sync::mpsc::{channel, Receiver, Sender};
use std::collections::HashMap;
use std::sync::{Arc, 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],
}
enum DroneCommand {
FoundSmall(TreasureLoc),
FoundBig(TreasureLoc),
Finished,
}
pub struct Drone {
index: usize,
tx: Sender<DroneCommand>,
stop: Arc<Mutex<bool>>,
}
impl Drone {
pub fn explore(&mut self, scanner: &mut dyn Iterator<Item = Scan<'_>>) {
while !*self.stop.lock().unwrap() {
let scan = match scanner.next() {
Some(s) => s,
None => break,
};
for (i, &value) in scan.cells.iter().enumerate() {
if *self.stop.lock().unwrap() {
break;
}
if value <= 0 {
continue;
}
let location = TreasureLoc {
lane_index: self.index,
cell_coord: scan.start_coord + i,
value,
};
if value >= 999 {
*self.stop.lock().unwrap() = true;
let _ = self.tx.send(DroneCommand::FoundBig(location));
break;
} else {
let _ = self.tx.send(DroneCommand::FoundSmall(location));
}
}
}
let _ = self.tx.send(DroneCommand::Finished);
}
}
pub struct DroneController {
tx: Sender<DroneCommand>,
rx: Receiver<DroneCommand>,
stop: Arc<Mutex<bool>>,
drones_count: usize,
}
impl DroneController {
pub fn new() -> Self {
let (tx, rx) = channel();
Self { tx, rx, stop: Arc::new(Mutex::new(false)), drones_count: 0,}
}
pub fn create_drone(&mut self, lane_index: usize) -> Drone {
self.drones_count += 1;
Drone {
index: lane_index,
tx: self.tx.clone(),
stop: Arc::clone(&self.stop),
}
}
pub fn run(&mut self) -> FoundTreasures {
let mut best_per_lane: HashMap<usize, TreasureLoc> = HashMap::new();
let mut sum_best: i32 = 0;
let mut active = self.drones_count;
while active > 0 {
let msg = match self.rx.recv() {
Ok(m) => m,
Err(_) => break,
};
match msg {
DroneCommand::FoundBig(location) => {
*self.stop.lock().unwrap() = true;
return FoundTreasures::Big(location);
}
DroneCommand::FoundSmall(location) => {
if *self.stop.lock().unwrap() {
continue;
}
match best_per_lane.get(&location.lane_index) {
None => {
sum_best += location.value;
best_per_lane.insert(location.lane_index, location);
}
Some(prev) if location.value > prev.value => {
sum_best += location.value - prev.value;
best_per_lane.insert(location.lane_index, location);
}
_ => {}
}
if sum_best >= 300 {
*self.stop.lock().unwrap() = true;
let mut result: Vec<TreasureLoc> = best_per_lane.values().cloned().collect();
result.sort_by_key(|t| t.lane_index);
return FoundTreasures::Small(result);
}
}
DroneCommand::Finished => {
active -= 1;
}
}
}
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 quote v1.0.42
   Compiling libc v0.2.178
   Compiling unicode-ident v1.0.22
   Compiling syn v2.0.111
   Compiling pin-project-lite v0.2.16
   Compiling parking_lot_core v0.9.12
   Compiling futures-sink v0.3.31
   Compiling futures-core v0.3.31
   Compiling futures-channel v0.3.31
   Compiling futures-io v0.3.31
   Compiling scopeguard v1.2.0
   Compiling memchr v2.7.6
   Compiling pin-utils v0.1.0
   Compiling slab v0.4.11
   Compiling cfg-if v1.0.4
   Compiling smallvec v1.15.1
   Compiling futures-task v0.3.31
   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-ecd4z5/solution)
warning: function `assert_send_static` is never used
   --> src/lib.rs:139:10
    |
139 | 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.36s
     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

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

Пламен качи първо решение на 23.12.2025 19:54 (преди около 1 месеца)