#!/usr/bin/perl

$c = 0;		# Counter
$t = 100000;	# Trials
$s = 0;		# Switch flag (0 doesn't switch, 1 switches)
$d = 3;		# Door with car; no loss of generality.

for($i = 0; $i < $t; $i++) {

  # Pick a door at random
  $p = int(rand(3)) + 1;

  # If I picked the car door, then pick $g, the goat door, from 1 and 2
  if ($d == $p) {$g = int(rand(2)) + 1;}

  # If I didn't pick the right door, pick $g as the last unassigned door
  else {$g = (3 - $p);}

  # Good programming trick here--the old (1 - t) trick, where 1 is the
  # sum of the two numbers and t is the variable.  This time we use
  # the element of $g as well.  We want to switch the user's chosen door
  # if s = 1.  If $g = 1, then $p is either 2 or 3, meaning t must be 5.
  # If $g = 2, then $p is either 1 or 3, meaning t must be 4.  If $g = 3,
  # then $p is either 1 or 2, meaning t must be 3.  t is equal to 6 - $g.

  if ($s == 1) {$p = (6 - $g) - $p;}

  # If I picked the right door, advance the counter by one.

  if ($p == $d) {$c++;}

}

# Print the results

$per = ($c / $t) * 100;
if($s == 0) {
  print "Without switching, the percentage is $per%\n";
}
else {
  print "With switching, the percentage is $per%\n";
} 

print "Edit the 5th line in hw4p1.pl to accomodate switching\n\n";
