Verbose commenting of code.

This commit is contained in:
Nicolás A. Ortega Froysa 2022-07-01 22:12:30 +02:00
parent aa2a5f6108
commit 9e66334c27

View File

@ -25,40 +25,54 @@
extern crate rand;
fn main() {
// set number of prisoners in experiment
let size = 100;
// initialize the boxes with randomly assigned numbers
// initialize the boxes with capacity for `size` number of boxes
let mut boxes:Vec<u32> = Vec::with_capacity(size as usize);
{
// create vector of numbers to select randomly from
let mut nums:Vec<u32> = (0..size).collect();
while nums.len() > 0
{
// get a random index for nums
let rand_i:usize = rand::random::<usize>() % nums.len();
// add that element to the boxes vector
boxes.push(nums[rand_i]);
// remove the entry from the nums vector
nums.remove(rand_i);
}
}
// have prisoners find their number
// assume that all the prisoners have found their number
let mut all_found = true;
// for every prisoner in the jail
for i in 0..size
{
// the next (first) box the prisoner is to open is the one with his number (`i`)
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 _j in 0..(size/2)
{
// if the number inside the box is his number
if boxes[next_box] == i
{
// assign `found` to true
found = true;
// stop looking through more boxes.
break;
}
else
{
// if not found set the next_box to the number contained in the current box
next_box = boxes[next_box] as usize;
}
}
// if a prisoner has not found his number in `size/2` attempts
if !found
{
all_found = false;