Create Prisoner structure to save results.

This commit is contained in:
Nicolás A. Ortega Froysa 2022-07-02 10:51:13 +02:00
parent 4f402b109d
commit 1c70d82a1e

View File

@ -26,6 +26,7 @@ extern crate rand;
use structopt::StructOpt; use structopt::StructOpt;
// define the commandline parameters
#[derive(StructOpt)] #[derive(StructOpt)]
#[structopt(about = "An implementation of the Skyum's Protocol.")] #[structopt(about = "An implementation of the Skyum's Protocol.")]
struct Opt struct Opt
@ -34,7 +35,17 @@ struct Opt
size:u32, size:u32,
} }
// define the prisoner data
struct Prisoner
{
// if the prisoner found his number
found:bool,
// number of attempt he found it in
attempts:u32,
}
fn main() { fn main() {
// read the commandline parameters
let opts = Opt::from_args(); let opts = Opt::from_args();
// set number of prisoners in experiment // set number of prisoners in experiment
@ -58,23 +69,30 @@ fn main() {
} }
} }
// assume that all the prisoners have found their number // create the vector of prisoners
let mut all_found = true; let mut prisoners:Vec<Prisoner> = Vec::with_capacity(size as usize);
// for every prisoner in the jail // for every prisoner in the jail
for i in 0..size for i in 0..size
{ {
// create the prisoner for index `i`
let mut prisoner_i = Prisoner {
// assume the prisoner does not find his box
found: false,
// set number of attempts to 0
attempts: 0,
};
// the next (first) box the prisoner is to open is the one with his number (`i`) // the next (first) box the prisoner is to open is the one with his number (`i`)
let mut next_box:usize = i as usize; let mut next_box:usize = i as usize;
// assume the prisoner does not find his box
let mut found = false;
// for every attempt the prisoner has (i.e. `size/2`) // for every attempt the prisoner has (i.e. `size/2`)
for _j in 0..(size/2) for _j in 0..(size/2)
{ {
prisoner_i.attempts += 1;
// if the number inside the box is his number // if the number inside the box is his number
if boxes[next_box] == i if boxes[next_box] == i
{ {
// assign `found` to true // assign `found` to true
found = true; prisoner_i.found = true;
// stop looking through more boxes. // stop looking through more boxes.
break; break;
} }
@ -84,20 +102,18 @@ fn main() {
next_box = boxes[next_box] as usize; next_box = boxes[next_box] as usize;
} }
} }
// if a prisoner has not found his number in `size/2` attempts
if !found // add prisoner to list of prisoners in experiment
{ prisoners.push(prisoner_i);
all_found = false;
}
} }
// print result // print result
if all_found if prisoners.iter().any(|i| !i.found)
{
println!("success");
}
else
{ {
println!("failure"); println!("failure");
} }
else
{
println!("success");
}
} }