#!/usr/bin/perl
randomize;

#
# Stick problem
# - If I make two cuts in a stick of length one, what are the chances that
#   the three sticks can form a triangle?  Mathematically, this means that
#   no stick is longer than the sum of the other two sticks.
# - Three different answers were given:
#   1) Two independent random cuts are made
#   2) One independent cut is made, and the second cut is made on the
#      right half (that is, if I start from the lefthand side and move up
#      the stick x units, then the second cut is made from the portion
#      that is (1 - x) units long.
#   3) One independent cut is made, and the second cut is made on the
#      larger of the two halves.
# - This simulation takes all three into consideration and actually
#   performs all three simultaneously.
#

$t = 10000;

for ($i = 0; $i < $t; $i++) {
  #
  # First Cut - Same for all
  #
  $firstCut[1] = rand;
  $firstCut[2] = rand;
  $firstCut[3] = rand;

  #
  # Second Cut for two unconditional cuts (part one)
  #
  $secondCut[1] = rand;

  #
  # Second Cut on rest of stick (part two for extra credit)
  #
  $secondCut[2] = rand(1 - $firstCut[2]) + $firstCut[2];

  #
  # Second Cut on bigger piece of stick (part three for extra credit)
  #
  if($firstCut[3] > 0.5) {
    $secondCut[3] = rand($firstCut[3]);
  } else {
    $secondCut[3] = rand(1 - $firstCut[3]) + $firstCut[3];
  }

  #
  # Swap Cuts if necessary and calculate winners
  #
  for ($j = 1; $j <= 3; $j++) {
    if($firstCut[$j] > $secondCut[$j]) {
      $d = $firstCut[$j];
      $firstCut[$j] = $secondCut[$j];
      $secondCut[$j] = $d;
    }

    # Process Cuts and add to counter if triangle is formed
    if($firstCut[$j] < 0.5 and $secondCut[$j] > 0.5 and ($secondCut[$j] - $firstCut[$j]) < 0.5) {
      $c[$j]++;
    }
  }
}

# Convert count results to odds results by dividing by number of trials
$c[1] /= $t;
$c[2] /= $t;
$c[3] /= $t;

print "Odds of triangles formed from unconditional cuts: $c[1]\n";
print "Odds of triangles formed from second cut on second half: $c[2]\n";
print "Odds of triangles formed from second cut on larger side: $c[3]\n";

