Task 1: Day of the Year
"Ordinal Numbers: Calculating Your Place in the Year!"
Given a date string in YYYY-MM-DD format, determine its ordinal day (1–365 or 1–366 for leap years).
The Strategy: First, parse the year, month, and day. Define an array of month lengths. A helper function (or inline logic) determines if the year is a leap year (divisible by 4, and either not divisible by 100 or divisible by 400), adjusting February's length to 29 if necessary. Sum the lengths of all months prior to the current month and add the current day.
Perl Implementation
sub is_leap {
my ($year) = @_;
return 0 if $year % 4;
return 1 if $year % 100;
return 0 if $year % 400;
return 1;
}
sub day_of_year {
my ($date) = @_;
my ($y, $m, $d) = split /-/, $date;
my @month_days = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
$month_days[2] = 29 if is_leap($y);
my $sum = $d;
$sum += $month_days[$_] for 1 .. $m - 1;
return $sum;
}
Python Implementation
def is_leap(year: int) -> bool:
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def day_of_year(date: str) -> int:
year, month, day = (int(part) for part in date.split("-"))
month_lengths = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap(year):
month_lengths[2] = 29
return day + sum(month_lengths[1:month])