You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.5 KiB

  1. use strict;
  2. my $iterations = 3000; # How many games to play
  3. my $verbosity = 0;
  4. while (@ARGV) {
  5. my $param = shift @ARGV;
  6. $verbosity = 1 if $param eq '-v';
  7. $iterations = int (shift @ARGV) if $param eq '-i';
  8. }
  9. sub verbose {
  10. print $_[0]."\\n" if $verbosity;
  11. }
  12. my $stickers;
  13. my $switchers;
  14. print "Playing $iterations games...\\n\\n";
  15. for(1..$iterations) {
  16. my @items = qw(goat goat prize); # two goats, one prize
  17. my @door;
  18. while (@items) { # this puts the @items into the @door array in random order
  19. push (@door, splice (@items, int rand @items, 1));
  20. }
  21. verbose ("Door 0: $door[0]; Door 1: $door[1]; Door 2: $door[2]");
  22. my $contestant = int rand 3;
  23. verbose ("Contestant chooses door $contestant.");
  24. my $monty;
  25. # If the contestant picked the prize, Monty picks another door by random.
  26. if ($door[$contestant] eq 'prize') {
  27. $monty = ($contestant + (int rand 2) + 1) % 3;
  28. }
  29. # Otherwise, he picks the other goat.
  30. else {
  31. $monty = $door [ ($contestant+1) % 3 ] eq 'goat' ? ($contestant+1) % 3 : ($contestant+2) % 3;
  32. }
  33. verbose ("Monty opens door $monty.");
  34. # Now only two doors are open. If the sticker wins, the switcher loses and vice versa.
  35. if ($door[$contestant] eq 'prize') {
  36. verbose ("Sticker wins. Switcher loses.");
  37. $stickers++;
  38. } else {
  39. verbose ("Sticker loses. Switcher wins.");
  40. $switchers++;
  41. }
  42. }
  43. print "Grand totals:
  44. Sticker has won $stickers times
  45. Switcher has won $switchers times
  46. ";