Perl Weekly Challenge: Week 401

Challenge 1:

Fractional Addition Subtraction

You are given a string representing an expression of fraction addition and substraction.

Write a script that returns the calculation result of given expression in string format. If final result is an integer, change it to the format of fraction that has a denominator 1.

Example 1
Input: $expr = "1/2+3/2"
Output: "2/1"

1/2 + 3/2 => 4/2 => 2

As specified by the rules, an integer result must be represented as a fraction with denominator 1, yielding "2/1".
Example 2
Input: $expr = "-5/2-3/2"
Output: "-4/1"

-5/2 - 3/2 => -8/2 => -4 => "-4/1".
Example 3
Input: $expr = "5/3-5/3"
Output: "0/1"

5/3 - 5/3 => 0/3
Zero divided by any valid non-zero denominator reduces to "0/1".
Example 4
Input: $expr = "10/10-1/10+2/5"
Output: "13/10"

10/10 - 1/10 + 2/5 => 9/10 + 4/10 => 13/10.
13/10 is already irreducible, so the output is "13/10".
Example 5
Input: $expr = "1/6+1/6+1/6"
Output: "1/2"

1/6 + 1/6 + 1/6 => 3/6 => 1/2

I think I did this problem once for a job interview long ago though not in Perl or Raku. In any case the algorithm to solve this is quite easy to implement.

The numerator and denominator of the resulting fraction have to be calculated separately. $denominator defaults to 1 because the spec says that should be the final format if the result is an integer.

my $numerator = 0;
my $denominator = 1;

We use a regular expression to pick out each fraction. The operators, + or -, are included as the sign of the $numerator.

my @terms = $expr.match(/ (<[+-]>? \d+) '/' (\d+) /, :g);

We go through each term (a possibly signed fraction) of the expression and add them by cross-multiplying their numerators and denominators to the already existing $numerator and $denominator.

for @terms -> ($termNumerator, $termDenominator) {
    # Add fractions by cross-multiplying their numerators and denominators.
    $numerator = $numerator * $termDenominator + $termNumerator * $denominator;
    $denominator = $denominator * $termDenominator;
}

Then we find the greatest common divisor (or 1 if there isn't any) to reduce the final fraction. Raku has a gcd operator which makes it easy.

my $commonDivisor = ($numerator.abs gcd $denominator.abs) || 1;

For reducing, we use the integer division operator div because you can't have a fractional part of a fraction.

$numerator div= $commonDivisor;
$denominator div= $commonDivisor;

And finally, we print the reduced result in fraction form.

say "$numerator/$denominator";

(Full code on Github.)

For Perl, we need a replacement for gcd which I already had.

my $numerator = 0;
my $denominator = 1;

my @terms = $expr =~ / ([+-]? \d+) \/ (\d+) /gx;

for my ($termNumerator, $termDenominator) (@terms) {

    $numerator = $numerator * $termDenominator + $termNumerator * $denominator;
    $denominator = $denominator * $termDenominator;
}

my $commonDivisor = gcd(abs($numerator), abs($denominator)) || 1;

We can work around the lack of div by using int() with normal division.

$numerator = int($numerator / $commonDivisor);
$denominator = int($denominator / $commonDivisor);

say "$numerator/$denominator";

(Full code on Github.)

Challenge 2:

Reconstruct Digits

You are given a string containing an out-of-order English representation of digits 0-9.

Write a script to return the digits in ascending order.

Example 1
Input: $str = "zroezerotwotwotwo"
Output: "00222"

'z' appears two times => two "zero"
'w' appears three times => three "two"
Example 2
Input: $str = "sveeeinght"
Output: "78"

'g' appears one time => one "eight"
Removing the letters of "eight" leaves "sveen".
Now 'v' appears one time => one "seven"
Example 3
Input: $str = "onenineninefive"
Output: "1599"

'f' appears one time => one "five"
After removing "five", 'o' appears one time => one "one".
The remaining letters are "ninenine", where 'i' appears two times => two "nine".
Example 4
Input: $str = "zeroonetwothreeeightfivesixsevenninefour"
Output: "0123456789"

The input contains the scrambled letters of every single digit from 0 through 9 exactly once:
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine".
Example 5
Input: $str = "ninenineninenine"
Output: "9999"

Character counts: 'n' = 8, 'i' = 4, 'e' = 4.
Every set of letters matches "nine", giving four 9s.

The, er, "challenging" thing about this challenge is that we have to account for number words not being spelled correctly or out of order (i.e. "zroe" in example 1 or "sveen" in example 2 which has intervening characters too.) So we can't just use simple regex substitutions to extract the digits. The spec does give a sort-of clue as to how me might proceed. If we can identify a character unique to a number word we can identify the word itself.

First we count each letter in $str so matched number words can be removed as they are found.

my %charCounts;
for $str.comb -> $char {
    %charCounts{$char}++;
}

The problem is all numbers do not have a unique identifying letter. For example only "zero" has a "z" in it but "one" doesn't have a single character which is not in other number words. So we have to organize the numbers in an order which lets us find and remove the more unique words first. I must confess I had to use Claude AI to get the final order shown here. Each row in the table below, has three fields; the key identifying letter, the full spelling of the number, and the number itself.

my @digitWords = (
    ['z', 'zero', 0],
    ['w', 'two', 2],
    ['u', 'four', 4],
    ['x', 'six', 6],
    ['g', 'eight', 8],
    ['o', 'one', 1],
    ['h', 'three', 3],
    ['f', 'five', 5],
    ['s', 'seven', 7],
    ['i', 'nine', 9],
);

We also need a Hash whose keys will be the digits, and values, the number of times each digit was found.

my %digitCounts;

Now we go through @digitWords row by row, destructuring the fields into separate variables.

for @digitWords -> ($keyChar, $word, $digit) {

We count how many time the key character occurs in $str. This will tells us how many of that digit occur.

    my $count = %charCounts{$keyChar} // 0;
    %digitCounts{$digit} = $count;

With this information we can remove very matched word so later identifying letters count only remaining words.

    for $word.comb -> $char {
        %charCounts{$char} -= $count;
    }
}

Finally we output each digit the number of times its word appeared, in ascending order.

my $output = '';
for 0..9 -> $digit {
    $output ~= $digit x (%digitCounts{$digit} // 0);
}
say $output;

(Full code on Github.)

The Perl version doesn't need any extra code for once.

my %charCounts;
for $str.comb -> $char {
    %charCounts{$char}++;
}

my @digitWords = (
    ['z', 'zero', 0],
    ['w', 'two', 2],
    ['u', 'four', 4],
    ['x', 'six', 6],
    ['g', 'eight', 8],
    ['o', 'one', 1],
    ['h', 'three', 3],
    ['f', 'five', 5],
    ['s', 'seven', 7],
    ['i', 'nine', 9],
);

my %digitCounts;
for @digitWords -> ($keyChar, $word, $digit) {
    my $count = %charCounts{$keyChar} // 0;
    %digitCounts{$digit} = $count;

    for $word.comb -> $char {
        %charCounts{$char} -= $count;
    }
}

my $output = '';
for 0..9 -> $digit {
    $output ~= $digit x (%digitCounts{$digit} // 0);
}
say $output;

(Full code on Github.)