Monty Hall problem: Difference between revisions
Content added Content deleted
(New Task with Python solution) |
|||
Line 8: | Line 8: | ||
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy. |
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy. |
||
=={{header|AWK}}== |
|||
<pre> |
|||
#!/bin/gawk -f |
|||
# Monty Hall problem |
|||
BEGIN { |
|||
srand() |
|||
doors = 3 |
|||
iterations = 10000 |
|||
# Behind a door: |
|||
EMPTY = "empty"; PRIZE = "prize" |
|||
# Algorithm used |
|||
KEEP = "keep"; SWITCH="switch"; RAND="random"; |
|||
# |
|||
} |
|||
function monty_hall( choice, algorithm ) { |
|||
# Set up doors |
|||
for ( i=0; i<doors; i++ ) { |
|||
door[i] = EMPTY |
|||
} |
|||
# One door with prize |
|||
door[int(rand()*doors)] = PRIZE |
|||
chosen = door[choice] |
|||
del door[choice] |
|||
#if you didn't choose the prize first time around then |
|||
# that will be the alternative |
|||
alternative = (chosen == PRIZE) ? EMPTY : PRIZE |
|||
if( algorithm == KEEP) { |
|||
return chosen |
|||
} |
|||
if( algorithm == SWITCH) { |
|||
return alternative |
|||
} |
|||
return rand() <0.5 ? chosen : alternative |
|||
} |
|||
function simulate(algo){ |
|||
prizecount = 0 |
|||
for(j=0; j< iterations; j++){ |
|||
if( monty_hall( int(rand()*doors), algo) == PRIZE) { |
|||
prizecount ++ |
|||
} |
|||
} |
|||
printf " Algorithm %7s: prize count = %i, = %6.2f%%\n", \ |
|||
algo, prizecount,prizecount*100/iterations |
|||
} |
|||
BEGIN { |
|||
print "\nMonty Hall problem simulation:" |
|||
print doors, "doors,", iterations, "iterations.\n" |
|||
simulate(KEEP) |
|||
simulate(SWITCH) |
|||
simulate(RAND) |
|||
} |
|||
</pre> |
|||
Sample output: |
|||
<pre> |
|||
bash$ ./monty_hall.awk |
|||
Monty Hall problem simulation: |
|||
3 doors, 10000 iterations. |
|||
Algorithm keep: prize count = 3411, = 34.11% |
|||
Algorithm switch: prize count = 6655, = 66.55% |
|||
Algorithm random: prize count = 4991, = 49.91% |
|||
bash$ |
|||
</pre> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
||
<python> |
<python> |