Решение на Домашно 1 - търсене на съкровища от Георги Стоянов
Резултати
- 20 точки от тестове
- 0 бонус точки
- 20 точки общо
- 5 успешни тест(а)
- 0 неуспешни тест(а)
Код
use std::collections::HashMap;
use std::thread;
use std::sync::{
atomic::{AtomicBool, Ordering},
mpsc,
mpsc::{Receiver, Sender},
Arc,
};
const BIG_THRESHOLD: i32 = 999;
const SMALL_TARGET_SUM: i32 = 300;
#[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 Msg {
Treasure(TreasureLoc),
Done,
}
pub struct Drone {
lane_index: usize,
tx: Sender<Msg>,
stop: Arc<AtomicBool>,
}
impl Drone {
pub fn explore(&mut self, scanner: &mut dyn Iterator<Item = Scan<'_>>) {
while !self.stop.load(Ordering::Relaxed) {
let Some(scan) = scanner.next() else {
break;
};
for (offset, &val) in scan.cells.iter().enumerate() {
if self.stop.load(Ordering::Relaxed) {
break;
}
if val <= 0 {
continue;
}
let loc = TreasureLoc {
lane_index: self.lane_index,
cell_coord: scan.start_coord + offset,
value: val,
};
let _ = self.tx.send(Msg::Treasure(loc.clone()));
if val >= BIG_THRESHOLD {
self.stop.store(true, Ordering::Relaxed);
break;
}
}
}
let _ = self.tx.send(Msg::Done);
}
}
pub struct DroneController {
tx: Sender<Msg>,
rx: Receiver<Msg>,
stop: Arc<AtomicBool>,
total_drones: usize,
}
impl DroneController {
pub fn new() -> Self {
let (tx, rx) = mpsc::channel::<Msg>();
Self {
tx,
rx,
stop: Arc::new(AtomicBool::new(false)),
total_drones: 0,
}
}
pub fn create_drone(&mut self, lane_index: usize) -> Drone {
self.total_drones += 1;
Drone {
lane_index,
tx: self.tx.clone(),
stop: Arc::clone(&self.stop),
}
}
pub fn run(&mut self) -> FoundTreasures {
if self.total_drones == 0 {
self.stop.store(true, Ordering::Relaxed);
return FoundTreasures::Nothing;
}
let mut done_count: usize = 0;
let mut best_small: HashMap<usize, TreasureLoc> = HashMap::new();
let mut small_sum: i32 = 0;
loop {
let msg = match self.rx.recv() {
Ok(m) => m,
Err(_) => {
self.stop.store(true, Ordering::Relaxed);
return FoundTreasures::Nothing;
}
};
match msg {
Msg::Treasure(loc) => {
if loc.value >= BIG_THRESHOLD {
self.stop.store(true, Ordering::Relaxed);
return FoundTreasures::Big(loc);
}
if loc.value > 0 {
match best_small.get(&loc.lane_index) {
None => {
small_sum += loc.value;
best_small.insert(loc.lane_index, loc);
}
Some(prev) => {
if loc.value > prev.value {
small_sum += loc.value - prev.value;
best_small.insert(loc.lane_index, loc);
}
}
}
if small_sum >= SMALL_TARGET_SUM {
self.stop.store(true, Ordering::Relaxed);
let mut v: Vec<TreasureLoc> =
best_small.values().cloned().collect();
v.sort_by(|a, b| {
a.lane_index
.cmp(&b.lane_index)
.then(a.cell_coord.cmp(&b.cell_coord))
.then(a.value.cmp(&b.value))
});
return FoundTreasures::Small(v);
}
}
}
Msg::Done => {
done_count += 1;
if done_count >= self.total_drones {
self.stop.store(true, Ordering::Relaxed);
return 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 libc v0.2.178
Compiling unicode-ident v1.0.22
Compiling syn v2.0.111
Compiling futures-sink v0.3.31
Compiling pin-project-lite v0.2.16
Compiling futures-core v0.3.31
Compiling parking_lot_core v0.9.12
Compiling futures-channel v0.3.31
Compiling cfg-if v1.0.4
Compiling scopeguard v1.2.0
Compiling futures-task v0.3.31
Compiling futures-io v0.3.31
Compiling pin-utils v0.1.0
Compiling memchr v2.7.6
Compiling slab v0.4.11
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 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-xg8yl6/solution)
warning: unused import: `std::thread`
--> src/lib.rs:2:5
|
2 | use std::thread;
| ^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
warning: `solution` (lib) generated 1 warning (run `cargo fix --lib -p solution` to apply 1 suggestion)
Finished `test` profile [unoptimized + debuginfo] target(s) in 17.64s
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
