The Bear's Den

Enter at your own risk

The Length of a Day

Task 1: Day of the Year

Submitted by: Mohammad Sajid Anwar


You are given a date in the format YYYY-MM-DD.

Write a script to find day number of the year that the given date represent.

Example 1

Input: $date = '2025-02-02'
Output: 33

The 2nd Feb, 2025 is the 33rd day of the year.

Example 2

Input: $date = '2025-04-10'
Output: 100

Example 3

Input: $date = '2025-09-07'
Output: 250

Solution

Never write your own calendar application!

Using DateTime::Format::Strptime to parse the given data and find the corresponding day of year.

use strict;
use warnings;
use DateTime::Format::Strptime;

use constant YMD => DateTime::Format::Strptime->new(pattern => '%F',
    on_error => 'croak');

sub day_of_year {
    YMD->parse_datetime(shift)->day_of_year;
}

See the full solution to task 1.

Task 2: Decompressed List

Submitted by: Mohammad Sajid Anwar


You are given an array of positive integers having even elements.

Write a script to to return the decompress list. To decompress, pick adjacent pair (i, j) and replace it with j, i times.

Example 1

Input: @ints = (1, 3, 2, 4)
Output: (3, 4, 4)

Pair 1: (1, 3) => 3 one time  => (3)
Pair 2: (2, 4) => 4 two times => (4, 4)

Example 2

Input: @ints = (1, 1, 2, 2)
Output: (1, 2, 2)

Pair 1: (1, 1) => 1 one time  => (1)
Pair 2: (2, 2) => 2 two times => (2, 2)

Example 3

Input: @ints = (3, 1, 3, 2)
Output: (1, 1, 1, 2, 2, 2)

Pair 1: (3, 1) => 1 three times => (1, 1, 1)
Pair 2: (3, 2) => 2 three times => (2, 2, 2)

Solution

PDL comes with two functions rle and rld for run-length encoding/decoding of 1-d ndarrays.

Their operation is slightly different from this task as encoding produces separate ndarrays for the lengths and the values. Accordingly, decoding requires two ndarrays as input.

Implementing both directions using these functions is a nice example to show some counterparts from PDL’s functions.

For encoding, rle is applied to the list, the resulting ndarrays are joined in a new second dimension to a N x 2 matrix that after transposition and the joining of the two dimensions into one generates a compressed list as it is used in this task.

This may look like:

use strict;
use warnings;
use PDL 2.017;

sub compressed_list {
    cat(rle long @_)->xchg(0, 1)->clump(2);
}

For decoding, the opposite actions need to be performed in reversed order: Take the list, split its single dimension into two, transpose the resulting matrix and split it along its last dimension. This produces the required input for rld and looks like:

sub decompressed_list {
    rld long(@_)->splitdim(0, 2)->xchg(0, 1)->dog;
}

Here we find the opposite function pairs rle - rld, cat - dog and clump - splitdim, while xchg is its own anti-function. Note dog’s POD:

dog
\(\quad\)Opposite of ‘cat’ :) […]

See the full solution to task 2.


If you have a question about this post or if you like to comment on it, feel free to open an issue in my github repository.