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"> |
<syntaxhighlight lang="chapel"> |
||
use Random; |
|||
param doors: int = 3; |
|||
config const games: int = 1000; |
|||
config const |
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 |
var switch, stick: uint; |
||
coforall task in tasks { |
|||
⚫ | |||
for game in 1..#games_per_task { |
|||
⚫ | |||
⚫ | |||
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 |
|||
⚫ | |||
{ |
|||
⚫ | |||
⚫ | |||
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"); |
|||
⚫ | |||
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." ); |
|||
} |
|||
⚫ | |||
Sample output: |
Sample output: |
||
<pre> |
<pre> |
||
Over 1000000 games: |
|||
Wins by staying: 354 or 35.4% |
|||
- switching wins 66.6937% of the time and |
|||
- sticking wins 33.3063% of the time |
|||
Switching is the superior method. |
|||
</pre> |
</pre> |
||