Решение на Домашно 1 - търсене на съкровища от Йоан Грозев

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

Към профила на Йоан Грозев

Резултати

  • 16 точки от тестове
  • 0 бонус точки
  • 16 точки общо
  • 4 успешни тест(а)
  • 1 неуспешни тест(а)

Код

use std::collections::HashMap;
use std::sync::mpsc::{self, Receiver, Sender, SyncSender};
use std::thread;
#[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,
treasure_pipe_out: SyncSender<TreasureLoc>,
stop_pipe_in: Receiver<()>,
}
pub struct DroneController
{
treasure_pipe_out: SyncSender<TreasureLoc>,
treasure_pipe_in: Receiver<TreasureLoc>,
stop_pipe_outs: HashMap<usize, Sender<()>>,
}
impl Drone
{
pub fn explore(&mut self, scanner: &mut dyn Iterator<Item = Scan<'_>>)
{
let mut best_value = 0;
let mut candidate_coord = 0;
for scan in scanner
{
if self.check_stop()
{
return;
}
for (i, &value) in scan.cells.iter().enumerate()
{
let coord = scan.start_coord + i;
if self.check_stop()
{
return;
}
if value > 0 && value > best_value
{
best_value = value;
candidate_coord = coord;
let treasure = TreasureLoc
{
lane_index: self.lane_index,
cell_coord: candidate_coord,
value: best_value,
};
if self.treasure_pipe_out.send(treasure).is_err()
{
return;
}
if self.check_stop()
{
return;
}
}
}
}
}
#[inline]
fn check_stop(&self) -> bool
{
self.stop_pipe_in.try_recv().is_ok()
}
}
impl DroneController
{
pub fn new() -> Self
{
let (treasure_pipe_out, treasure_pipe_in) = mpsc::sync_channel::<TreasureLoc>(0);
Self
{
treasure_pipe_out,
treasure_pipe_in,
stop_pipe_outs: HashMap::new(),
}
}
pub fn create_drone(&mut self, lane_index: usize) -> Drone
{
assert!(!self.stop_pipe_outs.contains_key(&lane_index),
"Drone on lane {} already exists!",
lane_index
);
let (stop_pipe_out, stop_pipe_in) = mpsc::channel::<()>();
self.stop_pipe_outs.insert(lane_index, stop_pipe_out);
Drone
{
lane_index,
treasure_pipe_out: self.treasure_pipe_out.clone(),
stop_pipe_in,
}
}
pub fn run(&mut self) -> FoundTreasures
{
let mut candidate_treasures: HashMap<usize, TreasureLoc> = HashMap::new();
while let Ok(treasure) = self.treasure_pipe_in.recv()
{
if treasure.value >= 999
{
self.send_stop_to_all();
return FoundTreasures::Big(treasure);
}
let should_replace = match candidate_treasures.get(&treasure.lane_index)
{
Some(existing) => treasure.value > existing.value,
None => true,
};
if should_replace
{
candidate_treasures.insert(treasure.lane_index, treasure);
let sum: i32 = candidate_treasures.values().map(|t| t.value).sum();
if sum >= 300
{
self.send_stop_to_all();
let mut treasures: Vec<TreasureLoc> =
candidate_treasures.into_values().collect();
treasures.sort_by_key(|t| t.lane_index);
return FoundTreasures::Small(treasures);
}
}
}
FoundTreasures::Nothing
}
fn send_stop_to_all(&self)
{
for stop_pipe_out in self.stop_pipe_outs.values()
{
let _ = stop_pipe_out.send(());
}
}
}
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 libc v0.2.178
   Compiling unicode-ident v1.0.22
   Compiling quote v1.0.42
   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 slab v0.4.11
   Compiling scopeguard v1.2.0
   Compiling cfg-if v1.0.4
   Compiling memchr v2.7.6
   Compiling pin-utils v0.1.0
   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-w4qzdz/solution)
warning: unused import: `std::thread`
 --> src/lib.rs:3:5
  |
3 | use std::thread;
  |     ^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

warning: value assigned to `candidate_coord` is never read
  --> src/lib.rs:46:17
   |
46 |         let mut candidate_coord = 0;
   |                 ^^^^^^^^^^^^^^^
   |
   = help: maybe it is overwritten before being read?
   = note: `#[warn(unused_assignments)]` on by default

warning: function `assert_send_static` is never used
   --> src/lib.rs:178:10
    |
178 | const fn assert_send_static<T: Send + 'static>() {}
    |          ^^^^^^^^^^^^^^^^^^
    |
    = note: `#[warn(dead_code)]` on by default

warning: `solution` (lib) generated 3 warnings (run `cargo fix --lib -p solution` to apply 1 suggestion)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 18.02s
     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_return_immediately_when_found ... ok
test solution_test::test_small_treasure ... ok
test solution_test::test_small_treasure_2 ... ok
test solution_test::test_nothing ... FAILED

failures:

---- solution_test::test_nothing stdout ----
thread 'solution_test::test_nothing' panicked at tests/solution_test.rs:234:60:
test timeout
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    solution_test::test_nothing

test result: FAILED. 4 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 3.00s

error: test failed, to rerun pass `--test solution_test`

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

Йоан качи първо решение на 23.12.2025 16:57 (преди около 1 месеца)