Perl Weekly Challenge: Week 103

Challenge 1:

Chinese Zodiac

You are given a year $year.

Write a script to determine the Chinese Zodiac for the given year $year. Please check out wikipage for more information about it.

The animal cycle: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.

The element cycle: Wood, Fire, Earth, Metal, Water.

Example 1
Input: 2017
Output: Fire Rooster
Example 2
Input: 1938
Output: Earth Tiger

As a time/date nerd I'll preface this by saying it is not completely accurate. The Chinese calander is lunar and the new year begins anywhere from mid-January to mid-February so just specifying the Gregorian year is not enough for a proper determination of the Chinese year. But it's good enough for our purposes.

All we need is two lookup tables in the form or arrays for the two elements of the Chinese year name, one for the element and one for the animal.

my @elements = < Metal Metal Water Water Wood Wood Fire Fire Earth Earth >;
my @animals = < Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat >;

Then we just use the $year modulo 10 for the element and modulo 12 for the animal to find the correct entries in the lookup tables.

say @elements[$year % 10], ' ', @animals[$year % 12];

(Full code on Github.)

The Perl version is just as easy.

my @elements = qw/ Metal Metal Water Water Wood Wood Fire Fire Earth Earth /;
my @animals = qw/ Monkey Rooster Dog Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat /;

say $elements[$year % 10], ' ', $animals[$year % 12];

(Full code on Github.)

Challenge 2:

What's Playing?

Working from home, you decided that on occasion you wanted some background noise while working. You threw together a network streamer to continuously loop through the files and launched it in a tmux (or screen) session, giving it a directory tree of files to play. During the day, you connected an audio player to the stream, listening through the workday, closing it when done.

For weeks you connect to the stream daily, slowly noticing a gradual drift of the media. After several weeks, you take vacation. When you return, you are pleasantly surprised to find the streamer still running. Before connecting, however, if you consider the puzzle of determining which track is playing.

After looking at a few modules to read info regarding the media, a quick bit of coding gave you a file list. The file list is in a simple CSV format, each line containing two fields: the first the number of milliseconds in length, the latter the media’s title (this example is of several episodes available from the MercuryTheatre.info):

1709363,"Les Miserables Episode 1: The Bishop (broadcast date: 1937-07-23)"
1723781,"Les Miserables Episode 2: Javert (broadcast date: 1937-07-30)"
1723781,"Les Miserables Episode 3: The Trial (broadcast date: 1937-08-06)"
1678356,"Les Miserables Episode 4: Cosette (broadcast date: 1937-08-13)"
1646043,"Les Miserables Episode 5: The Grave (broadcast date: 1937-08-20)"
1714640,"Les Miserables Episode 6: The Barricade (broadcast date: 1937-08-27)"
1714640,"Les Miserables Episode 7: Conclusion (broadcast date: 1937-09-03)"

For this script, you can assume to be provided the following information:

* the value of $^T ($BASETIME) of the streamer script,
* the value of time(), and
* a CSV file containing the media to play consisting of the length in milliseconds and an identifier for the media (title, filename, or other).

Write a program to output which file is currently playing. For purposes of this script, you may assume gapless playback, and format the output as you see fit.

Optional: Also display the current position in the media as a time-like value.

Examples

* UPDATED: Input parameters as reported by many members [2021-03-08 16:20 UK TIME]. Input: 3 command line parameters: start time, current time, file name *

    # starttime
    1606134123

    # currenttime
    1614591276

    # filelist.csv

Output:

    "Les Miserables Episode 1: The Bishop (broadcast date: 1937-07-23)"
    00:10:24

This one was tough only because the problem was (IMO) badly stated and the units are inconsistent. Once I worked all that out it was quite straightforward.

First we read in the CSV file. As the spec says, each record contains two fields so we convert the file to an array of two-element arrays. An issue that caused me trouble is that the length field in this file contains values in milliseconds whereas other values taken f

    my @streams = $csv.IO.lines.map({ [$_.split(',')] });

How long has the streamer been running? This formula gives the answer. We get both $start and $current in seconds so we have to multiply the answer by 1000 to get milliseconds.

    my $elapsed = ($current - $start) * 1000;

How much time has occurred since $start? This will also be in milliseconds but begins at 0.

    my $runtime = 0;

As the spec says, the streamer keeps playing the file list going through it and returning to the beginning when one complete cycle has occurred. We represent this by a double for-loop. The outer loop needs a label so we can distinguish from the inner loop.

    LOOP: loop {
        for @streams -> ($length, $description) {

$runtime also indicates the start of a track and $runtime + $length indicates its' end. If $elapsed falls between these two numbers we have found the right track...

            if $elapsed >= $runtime && $elapsed <= $runtime + $length {

...so we can print the $description.

                say $description;

The position within the track can be determined by subtracting $runtime from $elapsed. This time we want the value in seconds so we divide the answer by 1000.

                my $position = ($elapsed - $runtime) div 1000;

We then convert the position to hours, minutes and seconds and print it using .sprintf() for consistent formatting. Note in these calculations I have been using integer division and modulus with the div and mod operators instead of the usual / and % so we don't have to worry about fractions.

                say sprintf('%02d:%02d:%02d', $position div 3600,
                    $position mod 3600 div 60, $position mod 60);

Our work is now done so we can exit both loops.

                last LOOP;
            }

Otherwise if $elapsed was not in this track, we continue to the next one by adding $length to $runtime.

            $runtime += $length;
        }
    }

(Full code on Github.)

Opening and reading the CSV file is a bit more involved in Perl.

open my $fh, $csv or die "$OS_ERROR\n";
local $RS = undef;
my @streams = map { [ split q{,} ] } split "\n", <$fh>;
close $fh;

The rest is mostly the same as in Raku.

my $elapsed = ($current - $start) * 1000;
my $runtime = 0;

LOOP: while(true) {
    for my $stream (@streams) {
        my ($length, $description) = @{$stream};
        if ($elapsed >= $runtime && $elapsed <= $runtime + $length) {
            say $description;

We don't have div and mod so we need to convert the results of / and % ourselves using int().

            my $position = int (($elapsed - $runtime) / 1000);
            say sprintf('%02d:%02d:%02d', int($position / 3600),
                int(($position % 3600) / 60), $position % 60);
            last LOOP;
        }
        $runtime += $length;
    }
}

(Full code on Github.)