Monty Hall problem: Difference between revisions

no edit summary
No edit summary
Line 377:
Changing: 66.59
New random choice: 49.67
</pre>
 
=={{header|D}}==
<lang d>
import std.stdio, std.random;
 
void main() {
Random gen = Random(unpredictableSeed);
uint switchWins = 0, stayWins = 0;
 
while(switchWins + stayWins < 100_000) {
uint carPos = dice(gen, 1, 1, 1); // Which door is car behind?
uint pickPos = dice(gen, 1, 1, 1); // Contestant's initial pick.
uint openPos; // Which door is opened by Monty Hall?
 
// Monty can't open the door you picked or the one with the car
// behind it.
do {
openPos = dice(gen, 1, 1, 1);
} while(openPos == pickPos || openPos == carPos);
 
uint switchPos = 0;
// Find position that's not currently picked by contestant and was
// not opened by Monty already.
for(; pickPos == switchPos || openPos == switchPos; switchPos++) {}
 
if(pickPos == carPos) {
stayWins++;
} else if(switchPos == carPos) {
switchWins++;
} else {
assert(0); // Can't happen.
}
}
 
writefln("Switching wins: %d Staying wins: %d", switchWins, stayWins);
}
</lang>
 
Output:
<pre>
Switching wins: 66673 Staying wins: 33327
</pre>
 
Anonymous user