#!/usr/bin/perl #-------------------------------------------------------------------------------- # Monty Hall Trap #-------------------------------------------------------------------------------- $Number_of_games_to_play = 100; # Set to any number of games. $Doors = 3; # Total number of doors on the set $Reveal = -1; # >0 means to reveal that number or doors # <0 means to reveal $Doors+$Reveal-1 # (or just leave you with # one door to swap to) $Verbose = 1; # Print the results for each game $Swap_Option = 1; # -1 Never swap # 0 Sometimes swap # 1 Always swap doors #-------------------------------------------------------------------------------- # The following code plays the game and there is no need to change anything. #-------------------------------------------------------------------------------- # Set the reveal if its 0 or a negative number if ($Reveal < 1) { $Reveal = $Doors + $Reveal - 1; } die ("Reveal was too high.") if $Reveal >= ($Doors - 1); $Game_Number = 1; $Correct = 0; $Swapped = 0; for $Game_Number ( 1 .. $Number_of_games_to_play ) { #Seed the doors: @Door_Flags = (); for (1..$Doors) { push(@Door_Flags,' ') } $This_Games_Correct_Door = int(rand($Doors)+1); $Door_Flags[$This_Games_Correct_Door] = 'W'; print "Game $Game_Number: Door $This_Games_Correct_Door\n" if $Verbose; $This_Games_Guess = int(rand($Doors)+1); $Door_Flags[$This_Games_Guess] = 'G'; print "Game $Game_Number: Guess $This_Games_Guess\n" if $Verbose; for $r ( 1 .. $Reveal ) { $Game_Reveal = int(rand($Doors)+1); $break=0; while (($Door_Flags[$Game_Reveal]=~/\w/) && ($break < 10000)) { $break++; $Game_Reveal = int(rand($Doors)+1); } last if ($break >= 10000); $Door_Flags[$Game_Reveal] = 'R'; print "Game $Game_Number: Reveal $Game_Reveal\n" if $Verbose; } $Swap = ($Swap_Option) ? $Swap_Option+1 : int(rand(2)); if ($Swap) { $s=0; do {$s++} until (($Door_Flags[$s] ne 'R') && ($s != $This_Games_Guess)); $This_Games_Guess = $s; $Swapped++; print "Game $Game_Number: Changed my guess to $This_Games_Guess\n" if $Verbose; } if ($This_Games_Guess == $This_Games_Correct_Door) { print "YOU WIN!\n" if $Verbose; $Correct++; } else { print "You lose.\n" if $Verbose; } print "Doors: " . join('|',@Door_Flags) . "|\n" if $Verbose; print "\n" if $Verbose; } print "I played $Number_of_games_to_play games and won $Correct. I swapped my guess on $Swapped games.";