Jump to content

Monty Hall problem: Difference between revisions

→‎{{header|Chapel}}: re-implemented using data parallelism which is simpler and about 10× faster
imported>Myrmidon
(→‎{{header|Chapel}}: re-implemented using data parallelism which is simpler and about 10× faster)
Line 817:
 
=={{header|Chapel}}==
<syntaxhighlight lang="chapel">use Random;
 
use Random;
param doors: int = 3;
config const games: int = 1000;
 
config const maxTasksnumGames = 32100_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:switch, [tasks]stick: intuint;
 
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 player_doorchosen_door = (rand.getNext() * 1000): int % doors 3;
var winning_doorwinner_door = (rand.getNext() * 1000): int % doors 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:
<pre>
Over 1000000 games:
Wins by staying: 354 or 35.4%
Wins by - switching: 646wins or 6466.66937% of the time and
- sticking wins 33.3063% of the time
Switching is the superior method.
</pre>
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.