Skip to content

Commit 42ca8a7

Browse files
committed
doc: More efficient Monty Hall simulation
1 parent bf1ba83 commit 42ca8a7

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

src/libstd/rand/mod.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -95,12 +95,11 @@ use std::rand::distributions::{IndependentSample, Range};
9595
9696
struct SimulationResult {
9797
win: bool,
98-
switch: bool
98+
switch: bool,
9999
}
100100
101101
// Run a single simulation of the Monty Hall problem.
102-
fn simulate<R: Rng>(rng: &mut R) -> SimulationResult {
103-
let random_door = Range::new(0u, 3);
102+
fn simulate<R: Rng>(random_door: &Range<uint>, rng: &mut R) -> SimulationResult {
104103
let car = random_door.ind_sample(rng);
105104
106105
// This is our initial choice
@@ -121,32 +120,33 @@ fn simulate<R: Rng>(rng: &mut R) -> SimulationResult {
121120
// Returns the door the game host opens given our choice and knowledge of
122121
// where the car is. The game host will never open the door with the car.
123122
fn game_host_open<R: Rng>(car: uint, choice: uint, rng: &mut R) -> uint {
124-
let choices = free_doors(vec![car, choice]);
123+
let choices = free_doors(&[car, choice]);
125124
rand::sample(rng, choices.move_iter(), 1)[0]
126125
}
127126
128127
// Returns the door we switch to, given our current choice and
129128
// the open door. There will only be one valid door.
130129
fn switch_door(choice: uint, open: uint) -> uint {
131-
free_doors(vec![choice, open])[0]
130+
free_doors(&[choice, open])[0]
132131
}
133132
134-
fn free_doors(blocked: Vec<uint>) -> Vec<uint> {
133+
fn free_doors(blocked: &[uint]) -> Vec<uint> {
135134
range(0u, 3).filter(|x| !blocked.contains(x)).collect()
136135
}
137136
138137
fn main() {
139-
// The estimation will be more accuraty with more simulations
138+
// The estimation will be more accurate with more simulations
140139
let num_simulations = 10000u;
141140
142141
let mut rng = rand::task_rng();
142+
let random_door = Range::new(0u, 3);
143143
144144
let (mut switch_wins, mut switch_losses) = (0u, 0u);
145145
let (mut keep_wins, mut keep_losses) = (0u, 0u);
146146
147147
println!("Running {} simulations...", num_simulations);
148148
for _ in range(0, num_simulations) {
149-
let result = simulate(&mut rng);
149+
let result = simulate(&random_door, &mut rng);
150150
151151
match (result.win, result.switch) {
152152
(true, true) => switch_wins += 1,

0 commit comments

Comments
 (0)