Sunday, December 2, 2012

Birthday Paradox

Another exercise from programmingpraxis.com. Original post can be found here.

#!/usr/bin/php
<?php

if ($argc != 3) {
   echo "Usage ".__FILE__." <numberOfPeople> <loopCount>".PHP_EOL;
   exit;
}
$num = $argv[1];
$loops = $argv[2];

echo "Running $loops tests with $num people...".PHP_EOL;

$numDupes = 0;
$tenth = floor($loops/10);
for ($i = 1; $i <= $loops; $i++) {

   $peopleArr = array();
   $dupe = FALSE;
   do {
      $birthday = makeBirthday();
      if (isset($peopleArr[$birthday])) {
         //We found a duplicate...
         $dupe = TRUE;
         break;
      }
      $peopleArr[$birthday] = TRUE;
   } while (count($peopleArr) < $num);

   if ($dupe) {
      $numDupes++;
   }

   if ($i%$tenth == 0) {
      echo "After $i tests, ".round((($numDupes/$i)*100),2)."%".PHP_EOL;
   }
   set_time_limit(10);
}

$overlaps = Round((($numDupes/$loops)*100),2);
echo "Found overlapping birthdays ".$overlaps."% of the time...".PHP_EOL;

function makeBirthday () {
   if (mt_rand(1,4) == 4) { //leap year
      $max = 366;
   } else { //normal year
      $max = 365;
   }
   return mt_rand(1,$max);
}

Saturday, December 1, 2012

Taxicab Number Test

My take on a taxicab number test routine. The original exercise can be found here.

#!/usr/bin/php
<?php

if ($argc != 2) {
   echo "Usage cube.php <number>".PHP_EOL;
   exit;
}
$num = $argv[1];

echo "Finding cubes less than ".$num.PHP_EOL;

$factor = 1;
$arr = array();
$bottom = array();
$top = array();
$half = floor($num/2);
//Modified the below loop to parition the cubes while its generating them.
//Thus preventing another loop to partition the cubes
do {
   $cube = pow($factor,3);
   if ($cube <= $half) {
      $bottom[$cube] = $factor;
   } else {
      $top[$factor] = $cube;
   }
   $factor++;
} while ($cube < $num);

echo "Found ".count($top)." cubes > lower half of list".PHP_EOL;
echo "Found ".count($bottom)." cubes <= lower half of list".PHP_EOL;
$total = (count($top)+count($bottom));
$perc = count($top)/$total;
echo "Only testing ".(round($perc*100,2))."%".PHP_EOL;

foreach ($top as $factor => $product) {
   $remainder = $num-$product;
   if (isset($bottom[$remainder])) {
      echo "Found ".$factor."^3 + ".$bottom[$remainder]."^3 = ".$num.PHP_EOL;
   }
}