Verbose commenting of code.
This commit is contained in:
parent
aa2a5f6108
commit
9e66334c27
18
src/main.rs
18
src/main.rs
@ -25,40 +25,54 @@
|
|||||||
extern crate rand;
|
extern crate rand;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
|
// set number of prisoners in experiment
|
||||||
let size = 100;
|
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);
|
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();
|
let mut nums:Vec<u32> = (0..size).collect();
|
||||||
|
|
||||||
while nums.len() > 0
|
while nums.len() > 0
|
||||||
{
|
{
|
||||||
|
// get a random index for nums
|
||||||
let rand_i:usize = rand::random::<usize>() % nums.len();
|
let rand_i:usize = rand::random::<usize>() % nums.len();
|
||||||
|
// add that element to the boxes vector
|
||||||
boxes.push(nums[rand_i]);
|
boxes.push(nums[rand_i]);
|
||||||
|
// remove the entry from the nums vector
|
||||||
nums.remove(rand_i);
|
nums.remove(rand_i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// have prisoners find their number
|
// assume that all the prisoners have found their number
|
||||||
let mut all_found = true;
|
let mut all_found = true;
|
||||||
|
// for every prisoner in the jail
|
||||||
for i in 0..size
|
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;
|
let mut next_box:usize = i as usize;
|
||||||
|
// assume the prisoner does not find his box
|
||||||
let mut found = false;
|
let mut found = false;
|
||||||
|
// for every attempt the prisoner has (i.e. `size/2`)
|
||||||
for _j in 0..(size/2)
|
for _j in 0..(size/2)
|
||||||
{
|
{
|
||||||
|
// if the number inside the box is his number
|
||||||
if boxes[next_box] == i
|
if boxes[next_box] == i
|
||||||
{
|
{
|
||||||
|
// assign `found` to true
|
||||||
found = true;
|
found = true;
|
||||||
|
// stop looking through more boxes.
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
// if not found set the next_box to the number contained in the current box
|
||||||
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
|
if !found
|
||||||
{
|
{
|
||||||
all_found = false;
|
all_found = false;
|
||||||
|
Loading…
Reference in New Issue
Block a user