Monty Hall problem: Difference between revisions

Content added Content deleted
imported>Myrmidon
(→‎{{header|Chapel}}: re-implemented using data parallelism which is simpler and about 10× faster)
Line 817: Line 817:


=={{header|Chapel}}==
=={{header|Chapel}}==
<syntaxhighlight lang="chapel">use Random;
<syntaxhighlight lang="chapel">


use Random;
param doors: int = 3;
config const games: int = 1000;


config const maxTasks = 32;
config const numGames = 100_000_000;
var numTasks = 1;
while( games / numTasks > 1000000 && numTasks < maxTasks ) do numTasks += 1;
const tasks = 1..#numTasks;
const games_per_task = games / numTasks ;
const remaining_games = games % numTasks ;


var wins_by_stay: [tasks] int;
var switch, stick: uint;

coforall task in tasks {

var rand = new RandomStream();

for game in 1..#games_per_task {
var player_door = (rand.getNext() * 1000): int % doors ;
var winning_door = (rand.getNext() * 1000): int % doors ;
if player_door == winning_door then
wins_by_stay[ task ] += 1;
}
if task == tasks.last then {
for game in 1..#remaining_games {
var player_door = (rand.getNext() * 1000): int % doors ;
var winning_door = (rand.getNext() * 1000): int % doors ;
if player_door == winning_door then
wins_by_stay[ task ] += 1;
}
}


// have a separate RNG for each task; add together the results at the end
forall i in 1..numGames
with (var rand = new RandomStream(uint, parSafe = false), + reduce stick)
{
var chosen_door = rand.getNext() % 3;
var winner_door = rand.getNext() % 3;
if chosen_door == winner_door then
stick += 1;
}
}


// if you lost by sticking it means you would have won by switching
var total_by_stay = + reduce wins_by_stay;
switch = numGames - stick;
writeln("Over ", numGames, " games:\n - switching wins ",
100.0*switch / numGames, "% of the time and\n - sticking wins ",
100.0*stick / numGames, "% of the time");


</syntaxhighlight>
var total_by_switch = games - total_by_stay;
var percent_by_stay = ((total_by_stay: real) / games) * 100;
var percent_by_switch = ((total_by_switch: real) / games) * 100;


writeln( "Wins by staying: ", total_by_stay, " or ", percent_by_stay, "%" );
writeln( "Wins by switching: ", total_by_switch, " or ", percent_by_switch, "%" );
if ( total_by_stay > total_by_switch ){
writeln( "Staying is the superior method." );
} else if( total_by_stay < total_by_switch ){
writeln( "Switching is the superior method." );
} else {
writeln( "Both methods are equal." );
}
</syntaxhighlight>
Sample output:
Sample output:
<pre>
<pre>
Over 1000000 games:
Wins by staying: 354 or 35.4%
Wins by switching: 646 or 64.6%
- switching wins 66.6937% of the time and
- sticking wins 33.3063% of the time
Switching is the superior method.
</pre>
</pre>