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);
}

No comments:

Post a Comment