[Challenge] Friday the 13th
Posted: Sun Jul 18, 2010 1:02 pm
Calculate the number of Friday the 13th occurrences from the first day in 1900 through the end of 2010.
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
<?php
$fri13 = 0;
for($year = 1900; $year <= 2010; $year++) {
for($month = 1; $month <= 12; $month++) {
if(date('l', mktime(0, 0, 0, $month, 13, $year)) == "Friday") {
//print date("F Y", mktime(0, 0, 0, $month, 13, $year)) ." has a friday the 13th.\n";
$fri13++;
}
}
}
print"there are {$fri13} friday 13ths between 01-01-1900 and 31-12-2010.\n";
?>Code: Select all
<?php
$fri13 = 0;
for($year = 1900; $year <= 2010; $year++) {
for($month = 1; $month <= 12; $month++) {
$date = date_create("{$year}-{$month}-13");
if(date_format($date, "l") == "Friday") {
//print date_format($date, "Y m") ." has a friday the 13th.\n";
$fri13++;
}
}
}
print"there are {$fri13} friday 13ths between 01-01-1900 and 31-12-2010.\n";
?>Code: Select all
class Friday13Calculator
{
private static $fridays13inLeapYearWithWeekOffsets = array
(
1 => 2,
2 => 1,
3 => 2,
4 => 2,
5 => 1,
6 => 1,
7 => 3,
);
private static $fridays13inNonLeapYearWithWeekOffsets = array
(
1 => 2,
2 => 2,
3 => 1,
4 => 3,
5 => 1,
6 => 1,
7 => 2,
);
public static function get($startYear, $endYear)
{
$numberOfFridays13 = 0;
for ($year = $startYear; $year <= $endYear; $year++)
{
if (self::isLeapYear($year))
$fridays13InYear = self::$fridays13inLeapYearWithWeekOffsets;
else
$fridays13InYear = self::$fridays13inNonLeapYearWithWeekOffsets;
$numberOfFridays13 += $fridays13InYear[self::getWeekOffset($year)];
}
return $numberOfFridays13;
}
private static function isLeapYear($year)
{
if ($year % 4 != 0)
return false;
if ($year % 100 != 0)
return true;
if ($year % 400 != 0)
return false;
return true;
}
private static function getWeekOffset($year)
{
return date_format(date_create('01-01-'.$year), 'N');
}
}
echo Friday13Calculator::get(1900, 2010);
Code: Select all
for($i=0, $start=new DateTime('1900-01-13'), $end=new DateTime('2010-12-31'); $start<=$end; $start->modify('13 of next month')) {
if($start->format('N') == 5) {
$i++;
//$dates[] = $start->format('Y-m-d'); //if you need the dates
}
}
echo $i;EDIT: PHP v5.3.2-1ubuntu4.2Warning: DateTime::modify() [datetime.modify]: Failed to parse time string (13 of next month) at position 0 (1): Unexpected character ...
That's strange, runs great for me. Seems like they broke something between 5.2.4 and 5.3.2VladSun wrote:Hm, I'm getting a warning with your code:
EDIT: PHP v5.3.2-1ubuntu4.2Warning: DateTime::modify() [datetime.modify]: Failed to parse time string (13 of next month) at position 0 (1): Unexpected character ...
Code: Select all
echo 190;Same for you WeirdanAbraCadaver wrote:You're missing 4
Sorry, can't reproduce, please provide proper bugreportAbraCadaver wrote:Same for you Weirdan