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

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

Към профила на Никола

Резултати

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

Код

use std::sync::mpsc::{self, Receiver, Sender, SyncSender};
const fn assert_send_static<T: Send + 'static>() {}
const _: () = assert_send_static::<DroneController>();
const _: () = assert_send_static::<Drone>();
pub struct Scan<'a> {
// coord of first element in `cells`
pub start_coord: usize,
pub cells: &'a [i32],
}
#[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 DroneController {
sender: Sender<Msg>,
receiver: Receiver<Msg>,
done_senders: Vec<SyncSender<Done>>,
}
struct Done;
impl DroneController {
pub fn new() -> Self {
let (sender, receiver) = mpsc::channel();
DroneController {
sender,
receiver,
done_senders: vec![],
}
}
pub fn create_drone(&mut self, lane_index: usize) -> Drone {
let (done_sender, done_receiver) = mpsc::sync_channel(1);
self.done_senders.push(done_sender);
Drone::new(lane_index, self.sender.clone(), done_receiver)
}
pub fn run(&mut self) -> FoundTreasures {
let mut active_drones = self.done_senders.len();
let mut total_value_found = 0;
let mut small_treasures_per_lane: Vec<Option<TreasureLoc>> = (0..active_drones).map(|_| None).collect();
let mut big_treasure_loc = None;
for msg in self.receiver.iter() {
match msg {
Msg::NewMax(found_treasure) => {
let slot = &mut small_treasures_per_lane[found_treasure.lane_index];
let last_treasure_value = slot.as_ref().map(|t| t.value).unwrap_or(0);
total_value_found += found_treasure.value - last_treasure_value;
*slot = Some(found_treasure.clone());
if found_treasure.value >= 999 {
big_treasure_loc = Some(found_treasure);
break;
}
if total_value_found >= 300 {
break;
}
}
Msg::Exhausted { .. } => {
active_drones -= 1;
if active_drones == 0 {
break
}
}
}
}
for sender in &self.done_senders {
_ = sender.send(Done {});
}
if let Some(loc) = big_treasure_loc {
return FoundTreasures::Big(loc);
}
if total_value_found >= 300 {
small_treasures_per_lane.sort_by_key(|opt_t| match opt_t {
Some(t) => t.value,
None => 0,
});
let mut sum = 0;
let smalls = small_treasures_per_lane
.into_iter()
.filter_map(|t| t)
.map_while(|t| {
if sum < 300 {
sum += t.value;
Some(t)
} else {
None
}
})
.collect();
return FoundTreasures::Small(smalls);
}
FoundTreasures::Nothing
}
}
enum Msg {
NewMax(TreasureLoc),
Exhausted { _lane_index: usize },
}
pub struct Drone {
lane_index: usize,
sender: Sender<Msg>,
done_recv: Receiver<Done>,
}
impl Drone {
fn new(lane_index: usize, sender: Sender<Msg>, done_recv: Receiver<Done>) -> Self {
Drone {
lane_index,
sender,
done_recv,
}
}
pub fn explore(&mut self, scanner: &mut dyn Iterator<Item = Scan<'_>>) {
let mut max_treasure = None;
loop {
if let Ok(Done) = self.done_recv.try_recv() {
break;
}
let chunk = match scanner.next() {
Some(chunk) => chunk,
None => {
_ = self.sender.send(Msg::Exhausted { _lane_index: self.lane_index });
break;
}
};
let chunk_max = chunk.cells
.iter()
.enumerate()
.filter(|(_, val)| **val > 0)
.max_by_key(|(_, val)| *val);
match chunk_max {
Some((i, val)) if Some(*val) > max_treasure => {
max_treasure = Some(*val);
_ = self.sender.send(Msg::NewMax(TreasureLoc {
lane_index: self.lane_index,
cell_coord: chunk.start_coord + i,
value: *val,
}));
}
_ => {}
}
}
}
}

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

Updating crates.io index
     Locking 46 packages to latest compatible versions
   Compiling proc-macro2 v1.0.104
   Compiling libc v0.2.178
   Compiling quote v1.0.42
   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-core v0.3.31
   Compiling futures-sink v0.3.31
   Compiling futures-channel v0.3.31
   Compiling futures-task v0.3.31
   Compiling scopeguard v1.2.0
   Compiling cfg-if v1.0.4
   Compiling memchr v2.7.6
   Compiling slab v0.4.11
   Compiling futures-io v0.3.31
   Compiling smallvec v1.15.1
   Compiling pin-utils v0.1.0
   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 futures-macro v0.3.31
   Compiling tokio-macros v2.6.0
   Compiling mio v1.1.1
   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-1wml81f/solution)
warning: function `assert_send_static` is never used
 --> src/lib.rs:3:10
  |
3 | 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 19.07s
     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

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

Никола качи първо решение на 10.12.2025 12:09 (преди около 2 месеца)

Никола качи решение на 10.12.2025 14:10 (преди около 2 месеца)

use std::sync::mpsc::{self, Receiver, Sender, SyncSender};
const fn assert_send_static<T: Send + 'static>() {}
const _: () = assert_send_static::<DroneController>();
const _: () = assert_send_static::<Drone>();
pub struct Scan<'a> {
- pub start_offset: usize,
- pub area: &'a [i32],
+ // coord of first element in `cells`
+ pub start_coord: usize,
+ pub cells: &'a [i32],
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TreasureLoc {
pub lane_index: usize,
- pub offset: usize,
+ pub cell_coord: usize,
pub value: i32,
}
#[derive(Debug, PartialEq, Eq)]
pub enum FoundTreasures {
Big(TreasureLoc),
Small(Vec<TreasureLoc>),
Nothing,
}
pub struct DroneController {
sender: Sender<Msg>,
receiver: Receiver<Msg>,
done_senders: Vec<SyncSender<Done>>,
}
struct Done;
impl DroneController {
pub fn new() -> Self {
let (sender, receiver) = mpsc::channel();
DroneController {
sender,
receiver,
done_senders: vec![],
}
}
pub fn create_drone(&mut self, lane_index: usize) -> Drone {
let (done_sender, done_receiver) = mpsc::sync_channel(1);
self.done_senders.push(done_sender);
Drone::new(lane_index, self.sender.clone(), done_receiver)
}
pub fn run(&mut self) -> FoundTreasures {
let mut active_drones = self.done_senders.len();
let mut total_value_found = 0;
let mut small_treasures_per_lane: Vec<Option<TreasureLoc>> = (0..active_drones).map(|_| None).collect();
let mut big_treasure_loc = None;
for msg in self.receiver.iter() {
match msg {
Msg::NewMax(found_treasure) => {
let slot = &mut small_treasures_per_lane[found_treasure.lane_index];
let last_treasure_value = slot.as_ref().map(|t| t.value).unwrap_or(0);
total_value_found += found_treasure.value - last_treasure_value;
*slot = Some(found_treasure.clone());
if found_treasure.value >= 999 {
big_treasure_loc = Some(found_treasure);
break;
}
if total_value_found >= 300 {
break;
}
}
Msg::Exhausted { .. } => {
active_drones -= 1;
if active_drones == 0 {
break
}
}
}
}
for sender in &self.done_senders {
_ = sender.send(Done {});
}
if let Some(loc) = big_treasure_loc {
return FoundTreasures::Big(loc);
}
if total_value_found >= 300 {
small_treasures_per_lane.sort_by_key(|opt_t| match opt_t {
Some(t) => t.value,
None => 0,
});
let mut sum = 0;
let smalls = small_treasures_per_lane
.into_iter()
.filter_map(|t| t)
.map_while(|t| {
if sum < 300 {
sum += t.value;
Some(t)
} else {
None
}
})
.collect();
return FoundTreasures::Small(smalls);
}
FoundTreasures::Nothing
}
}
enum Msg {
NewMax(TreasureLoc),
Exhausted { _lane_index: usize },
}
pub struct Drone {
lane_index: usize,
sender: Sender<Msg>,
done_recv: Receiver<Done>,
}
impl Drone {
fn new(lane_index: usize, sender: Sender<Msg>, done_recv: Receiver<Done>) -> Self {
Drone {
lane_index,
sender,
done_recv,
}
}
pub fn explore(&mut self, scanner: &mut dyn Iterator<Item = Scan<'_>>) {
let mut max_treasure = None;
loop {
if let Ok(Done) = self.done_recv.try_recv() {
break;
}
let chunk = match scanner.next() {
Some(chunk) => chunk,
None => {
_ = self.sender.send(Msg::Exhausted { _lane_index: self.lane_index });
break;
}
};
- let chunk_max = chunk.area.iter().enumerate().max_by_key(|(_, val)| *val);
+ let chunk_max = chunk.cells.iter().enumerate().max_by_key(|(_, val)| *val);
match chunk_max {
Some((i, val)) if Some(*val) > max_treasure => {
max_treasure = Some(*val);
_ = self.sender.send(Msg::NewMax(TreasureLoc {
lane_index: self.lane_index,
- offset: i,
+ cell_coord: i,
value: *val,
}));
}
_ => {}
}
}
}
}

Никола качи решение на 10.12.2025 14:23 (преди около 2 месеца)

use std::sync::mpsc::{self, Receiver, Sender, SyncSender};
const fn assert_send_static<T: Send + 'static>() {}
const _: () = assert_send_static::<DroneController>();
const _: () = assert_send_static::<Drone>();
pub struct Scan<'a> {
// coord of first element in `cells`
pub start_coord: usize,
pub cells: &'a [i32],
}
#[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 DroneController {
sender: Sender<Msg>,
receiver: Receiver<Msg>,
done_senders: Vec<SyncSender<Done>>,
}
struct Done;
impl DroneController {
pub fn new() -> Self {
let (sender, receiver) = mpsc::channel();
DroneController {
sender,
receiver,
done_senders: vec![],
}
}
pub fn create_drone(&mut self, lane_index: usize) -> Drone {
let (done_sender, done_receiver) = mpsc::sync_channel(1);
self.done_senders.push(done_sender);
Drone::new(lane_index, self.sender.clone(), done_receiver)
}
pub fn run(&mut self) -> FoundTreasures {
let mut active_drones = self.done_senders.len();
let mut total_value_found = 0;
let mut small_treasures_per_lane: Vec<Option<TreasureLoc>> = (0..active_drones).map(|_| None).collect();
let mut big_treasure_loc = None;
for msg in self.receiver.iter() {
match msg {
Msg::NewMax(found_treasure) => {
let slot = &mut small_treasures_per_lane[found_treasure.lane_index];
let last_treasure_value = slot.as_ref().map(|t| t.value).unwrap_or(0);
total_value_found += found_treasure.value - last_treasure_value;
*slot = Some(found_treasure.clone());
if found_treasure.value >= 999 {
big_treasure_loc = Some(found_treasure);
break;
}
if total_value_found >= 300 {
break;
}
}
Msg::Exhausted { .. } => {
active_drones -= 1;
if active_drones == 0 {
break
}
}
}
}
for sender in &self.done_senders {
_ = sender.send(Done {});
}
if let Some(loc) = big_treasure_loc {
return FoundTreasures::Big(loc);
}
if total_value_found >= 300 {
small_treasures_per_lane.sort_by_key(|opt_t| match opt_t {
Some(t) => t.value,
None => 0,
});
let mut sum = 0;
let smalls = small_treasures_per_lane
.into_iter()
.filter_map(|t| t)
.map_while(|t| {
if sum < 300 {
sum += t.value;
Some(t)
} else {
None
}
})
.collect();
return FoundTreasures::Small(smalls);
}
FoundTreasures::Nothing
}
}
enum Msg {
NewMax(TreasureLoc),
Exhausted { _lane_index: usize },
}
pub struct Drone {
lane_index: usize,
sender: Sender<Msg>,
done_recv: Receiver<Done>,
}
impl Drone {
fn new(lane_index: usize, sender: Sender<Msg>, done_recv: Receiver<Done>) -> Self {
Drone {
lane_index,
sender,
done_recv,
}
}
pub fn explore(&mut self, scanner: &mut dyn Iterator<Item = Scan<'_>>) {
let mut max_treasure = None;
loop {
if let Ok(Done) = self.done_recv.try_recv() {
break;
}
let chunk = match scanner.next() {
Some(chunk) => chunk,
None => {
_ = self.sender.send(Msg::Exhausted { _lane_index: self.lane_index });
break;
}
};
- let chunk_max = chunk.cells.iter().enumerate().max_by_key(|(_, val)| *val);
+ let chunk_max = chunk.cells
+ .iter()
+ .enumerate()
+ .filter(|(_, val)| **val > 0)
+ .max_by_key(|(_, val)| *val);
+
match chunk_max {
Some((i, val)) if Some(*val) > max_treasure => {
max_treasure = Some(*val);
_ = self.sender.send(Msg::NewMax(TreasureLoc {
lane_index: self.lane_index,
- cell_coord: i,
+ cell_coord: chunk.start_coord + i,
value: *val,
}));
}
_ => {}
}
}
}
}