The Weekly Challenge 326

Ordinal Dates & List Decompression!

Original Challenge Link | Solutions on GitHub

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])

Task 2: Decompressed List

"Unfolding Arrays: Expanding Value-Count Pairs!"

Decompress an even-length array where adjacent pairs (i, j) represent value j repeated i times.

The Strategy: Iterate through the input array with a step of 2. In each iteration, take the first element of the pair as the 'count' and the second as the 'value'. Append the 'value' to the result list 'count' number of times.
Perl Implementation
sub decompress_list {
    my (@ints) = @_;
    my @out;
    for (my $i = 0; $i < @ints; $i += 2) {
        my ($count, $value) = @ints[$i, $i + 1];
        push @out, ($value) x $count;
    }
    return \@out;
}
Python Implementation
def decompress_list(ints: list[int]) -> list[int]:
    out: list[int] = []
    for i in range(0, len(ints), 2):
        count, value = ints[i], ints[i + 1]
        out.extend([value] * count)
    return out