Решение на Домашно 1 - търсене на съкровища от Илиян Свечев

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

Към профила на Илиян Свечев

Резултати

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

Код

use std::sync::{Arc, mpsc};
use std::sync::mpsc::{Sender, Receiver};
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::Relaxed;
#[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> {
// coord of first element in `cells`
pub start_coord: usize,
pub cells: &'a [i32],
}
pub struct Drone {
pub lane_index: usize,
pub sender: Sender<Message>,
pub stop_flag: Arc<AtomicBool>,
pub curr_best_value: i32,
}
impl Drone {
pub fn explore(&mut self, scanner: &mut dyn Iterator<Item = Scan<'_>>) {
while let Some(Scan {start_coord, cells}) = scanner.next() {
for (i, value) in cells.iter().enumerate() {
if self.stop_flag.load(Relaxed) {
return;
}
if *value > self.curr_best_value {
self.curr_best_value = *value;
let _ = self.sender.send(
Message::Treasure(TreasureLoc
{ lane_index: self.lane_index,
cell_coord: start_coord + i,
value: *value,
}));
}
if *value >= 999 {
// the new treasure was big, we're done
return;
}
}
}
let _ = self.sender.send(Message::Over());
}
}
pub enum Message {
Treasure(TreasureLoc),
Over(),
}
pub struct DroneController {
pub lane_best_treasure: HashMap<usize, TreasureLoc>,
pub receiver: Receiver<Message>,
pub sender: Sender<Message>,
pub stop_flag: Arc<AtomicBool>,
pub drone_count: usize,
}
impl DroneController {
pub fn new() -> Self {
let (sender, receiver) = mpsc::channel();
DroneController { lane_best_treasure: HashMap::new(),
receiver: receiver,
sender: sender,
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 {
lane_index: lane_index,
sender: self.sender.clone(),
stop_flag: self.stop_flag.clone(),
curr_best_value: 0
}
}
pub fn run(&mut self) -> FoundTreasures {
let mut finished_drones = 0;
let mut treasure_sum = 0;
let mut small_treasures = Vec::new();
while let Ok(msg) = self.receiver.recv() {
match msg {
Message::Over() => {
finished_drones += 1;
if finished_drones == self.drone_count {
self.stop_flag.store(true, Relaxed);
}
}
Message::Treasure(treasure) => {
// big treasure, we are done:
if treasure.value >= 999 {
self.stop_flag.store(true, Relaxed);
return FoundTreasures::Big(treasure.clone());
}
// small treasure:
let lane = treasure.lane_index;
let old_treasure_maybe = self.lane_best_treasure.get(&lane);
let old_val = match old_treasure_maybe {
Some(treasure) => {treasure.value}
None => {0}
};
let new_val = treasure.value;
if new_val > old_val {
treasure_sum += new_val - old_val;
self.lane_best_treasure.insert(lane, treasure.clone());
// small treasures are worth 300, we are done:
if treasure_sum >= 300 {
for found_treasure in self.lane_best_treasure.values() {
small_treasures.push(found_treasure.clone());
}
self.stop_flag.store(true, Relaxed);
return FoundTreasures::Small(small_treasures.clone());
}
}
}
}
// we break out when: everyone is done (flag raised)
if self.stop_flag.load(Relaxed) {
break;
}
}
FoundTreasures::Nothing
}
}

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

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-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 pin-utils v0.1.0
   Compiling memchr v2.7.6
   Compiling scopeguard v1.2.0
   Compiling smallvec v1.15.1
   Compiling slab v0.4.11
   Compiling cfg-if v1.0.4
   Compiling futures-task v0.3.31
   Compiling futures-io 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 socket2 v0.6.1
   Compiling mio v1.1.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-1dnk49u/solution)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 17.46s
     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 коментара)

Илиян качи първо решение на 18.12.2025 23:42 (преди около 1 месеца)