Perl Weekly Challenge: Zydeco? Why Zydeco?

Perl Weekly Challenge 401‘s tasks are “Fractional Addition Subtraction” and “Reconstruct Digits”.

I was talking about the tasks with my wife, and when I said “addition subtraction”, she immediately honed in on this old (old? This is from the 90s!) Sesame Street song, Adding Song. I like it because, initially, it’s adding powers of two (and it finishes off with 9 and 10); but my wife loves it because it’s classic Frank Oz taking the piss out of a middling routine and making it 1000% better, and I have to admit she’s right. “Ernie! This is not normal, you singing like this. You understand? Okay?” And then when Ernie adds two more to the two of them, in walk Grover and Cookie Monster, Oz’s other two big characters on the show. It’s all a big in-joke.

I’ll spare you from more Muppet geekery; let’s dive into this week’s challenge…

Task 1: Fractional Addition Subtraction

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

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

Approach

Ok, the first part of this problem is parsing the expression. Each of the fractions is a numerator with or without a sign, the slash, and then a denominator without a sign. If we make the operator between multiple fractions part of the numerator’s sign, then all the operations become addition (“5/3-5/3” is the same as “5/3” + “-5/3”). Then we perform the additions (adjusting the denominators as we go so they stay consistent), and then finally we simplify the fraction.

Raku

Since we’re parsing strings, I desperately wanted to use a Raku grammar to do so. Then I decided to break up the parts of my approach into separate subroutines: one for parsing the fractions, one for adding two fractions together, and one for simplifying a fraction and returning it as a string. I’m representing the fractions as arrays of [numerator, denominator].

grammar Fraction {
  token TOP { <numerator> \/ <denominator> <remaining> }
  token sign { <[ + \- ]> }
  token digits { \d+ }
  token integerNumber { <sign>? <digits> }
  token numerator { <integerNumber> }
  token denominator { <integerNumber> }
  token remaining { .* }
}

sub parseFractions($expr is copy) {
  my @fractions;
  while (my $parsed = Fraction.parse($expr)) {
    @fractions.push([
      $parsed<numerator>.Int, $parsed<denominator>.Int
    ]);
    $expr = $parsed<remaining>.Str;
  }
  @fractions;
}

sub addFractions($A, $B) {
  if ($A[1] != $B[1]) {
    # the denominators don't match, so let's make them match
    ($A[0], $A[1],
     $B[0], $B[1]) =
    ($A[0] * $B[1], $A[1] * $B[1],
     $B[0] * $A[1], $B[1] * $A[1])
  }
  my $sum = $A[0] + $B[0];
  [$sum, $A[1]];
}

sub simplifyFraction($A, $B) {
   my $d = $A gcd $B;
   join "/", $A / $d, $B / $d;
}

sub fractionalAdditionSubstraction($expr is copy) {
  my @fractions = parseFractions($expr);

  while (@fractions.elems >= 2) {
    @fractions.push(
      addFractions(@fractions.shift, @fractions.shift)
    );
  }
  simplifyFraction(@fractions[0][0], @fractions[0][1]);
}

View the entire Raku script for this task on GitHub.

$ raku/ch-1.raku
Example 1
Input: $expr = "1/2+3/2"
Output: "2/1"

Example 2
Input: $expr = "-5/2-3/2"
Output: "-4/1"

Example 3
Input: $expr = "5/3-5/3"
Output: "0/1"

Example 4
Input: $expr = "10/10-1/10+2/5"
Output: "13/10"

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

Perl

In Perl, I wound up using regular expressions with named captures instead of a grammar, which worked just as well. It’s even a little shorter than the Raku version.

The Math::Utils::gcd function doesn’t like being passed 0 as one of the values, so I added a special case on line 35.

use Math::Utils qw( gcd );

my $sign = qr/ [ + \- ] /x;
my $digits = qr/ \d+ /x;
my $integerNumber = qr/ $sign? $digits /x;
my $numerator = qr/ (?<numerator> $integerNumber ) /x;
my $denominator = qr/ (?<denominator> $integerNumber ) /x;
my $TOP  = qr/^ $numerator \/ $denominator (?<remaining> .* ) $/x;

sub parseFractions($expr) {
  my @fractions;
  while ($expr =~ /$TOP/) {
    push @fractions, [ $+{numerator}, $+{denominator} ];
    $expr = $+{remaining};
  }
  @fractions;
}

sub addFractions($A, $B) {
  if ($A->[1] != $B->[1]) {
    # the denominators don't match, so let's make them match
    ($A->[0], $A->[1],
     $B->[0], $B->[1]) =
    ($A->[0] * $B->[1], $A->[1] * $B->[1],
     $B->[0] * $A->[1], $B->[1] * $A->[1])
  }
  my $sum = $A->[0] + $B->[0];
  [$sum, $A->[1]];
}

sub simplifyFraction($A, $B) {
  return "0/1" if $A == 0;
  my $d = gcd([$A, $B]);
  join "/", $A / $d, $B / $d;
}

sub fractionalAdditionSubstraction($expr) {
  my @fractions = parseFractions($expr);
  while (@fractions >= 2) {
    push @fractions,
      addFractions(shift @fractions, shift @fractions);
  }
  simplifyFraction($fractions[0]->[0], $fractions[0]->[1]);
}

View the entire Perl script for this task on GitHub.

Python

The Python solution works pretty much exactly the way the Perl solution does.

import math
import re

sign = r'[+\-]'
digits = r'\d+'
integerNumber = fr' {sign}? {digits} '
numerator = fr' (?P<numerator> {integerNumber} ) '
denominator = fr' (?P<denominator> {integerNumber} ) '
TOP = re.compile(fr"""
^ {numerator} \/ {denominator} (?P<remaining> .* ) $
""",
  re.VERBOSE
)

def parse_fractions(expr):
  fractions = []
  while parsed := TOP.search(expr):
    fractions.append([
      int(parsed.group('numerator')),
      int(parsed.group('denominator'))
    ])
    expr = parsed.group('remaining')
  return fractions

def add_fractions(A, B):
  if A[1] != B[1]:
    # the denominators don't match, so let's make them match
    (A[0],        A[1],        B[0],        B[1]) = (
     A[0] * B[1], A[1] * B[1], B[0] * A[1], B[1] * A[1]
    )
  s = A[0] + B[0]
  return [s, A[1]]

def simplify_fraction(A, B):
  if A == 0: return "0/1"
  d = math.gcd(A, B)
  return f'{A // d}/{B // d}'

def fractional_addition_substraction(expr):
  fractions = parse_fractions(expr)
  while (len(fractions) >= 2):
    fractions.append(
      add_fractions(fractions.pop(0), fractions.pop(0))
    )
  return simplify_fraction(fractions[0][0], fractions[0][1])

View the entire Python script for this task on GitHub.

Elixir

In Elixir, I decided to switch from arrays to hold the individual fractions to maps with predefined atom keys :numerator and :denominator; this would allow me to use the named access mode and make my code a little neater.

@top ~r/^
  (?<numerator> [+-]? \d+ ) \/ (?<denominator> [+-]? \d+ )
  (?<remaining> .* )
$ /ux

defp int(val) when is_integer(val), do: val
defp int(val) when is_float(val), do: trunc(val)
defp int(val), do: String.to_integer(val)

def parse_fractions(expr, fractions) do
  parsed = Regex.named_captures(@top, expr)

  fractions =
    fractions ++
      [
        %{
          numerator: int(parsed["numerator"]),
          denominator: int(parsed["denominator"])
        }
      ]

  if parsed["remaining"] != "" do
    parse_fractions(parsed["remaining"], fractions)
  else
    fractions
  end
end

def add_fractions(a, b) do
  {a, b} =
    if a.denominator != b.denominator do
      {anum, adenom, bnum, bdenom} =
        {a.numerator * b.denominator,
         a.denominator * b.denominator,
         b.numerator * a.denominator,
         b.denominator * a.denominator}

      {%{numerator: anum, denominator: adenom},
       %{numerator: bnum, denominator: bdenom}}
    else
      {a, b}
    end

  sum = a.numerator + b.numerator
  %{numerator: sum, denominator: a.denominator}
end

def simplify_fraction(%{
      numerator: numerator,
      denominator: denominator
    }) do
  if numerator == 0 do
    "0/1"
  else
    d = Integer.gcd(numerator, denominator)
    "#{int(numerator / d)}/#{int(denominator / d)}"
  end
end

def fractional_addition_substraction(expr) do
  parse_fractions(expr, [])
  |> Enum.reduce(fn a, b -> add_fractions(a, b) end)
  |> simplify_fraction()
end

View the entire Elixir script for this task on GitHub.


Task 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.

Approach

Ok, so this is about counting characters, which means it’s time for a BAG! We’ll use a bag to get a character count of each of the characters in the string, and then we’ll find when there are multiples of the characters in each word and subtract them from the bag, until we don’t have any characters left.

One of the things I realized fairly early is that we want to be careful about the order in which we look for characters. For example, we can be fairly certain that if there’s a “z” in the bag, one of the input words was “zero”. But if we have an “o”, an “n”, and an “e”, it could mean that one of the input words was “one”, or it could mean that the “o” came from “two” and the “n” and “e” came from “seven”. So I ordered the way we’re looking for digits so the numbers that have unique characters came first—0 (it has a “z”), 2 (it has a “w”), 4 (it has a “u”), 6 (it has an “x”), 8 (it has a “g”)—then I just listed the remaining digits in descending order. But I found that when I did that, “nine” started stealing characters in example 4. When the string was down to “onethreefiveseven”, we could get another “nine” out of that, leaving “othreefveseve”. So I moved 9 to the end. I also whipped up example 6 which looks like it should have a “one”, but it’s just “twoseven”.

Raku

First, built my list of bags with character counts outside the function, because I only needed to calculate those once. Then, for each string, I calculated the bag as a BagHash because in Raku, the Bag class is immutable, and I wanted to be able to remove elements from it as I went along.

Fortunately, the subset operator (⊆) was able to determine if a bag is a subset of another bag, and I was able to use that to determine if a word’s bag appeared in the bag of characters from the string.

my @num_bag = [
  "zero".comb.Bag,
  "one".comb.Bag,
  "two".comb.Bag,
  "three".comb.Bag,
  "four".comb.Bag,
  "five".comb.Bag,
  "six".comb.Bag,
  "seven".comb.Bag,
  "eight".comb.Bag,
  "nine".comb.Bag
];

sub reconstructDigits($str) {
  my $charbag = $str.comb.BagHash;
  my @output;
  for [0,2,4,6,8,7,5,3,1,9] -> $digit {
    while ( @num_bag[$digit] ⊆ $charbag ) {
      @output.append($digit);
      $charbag.remove(@num_bag[$digit].kxxv);
    }
  }
  die "{@output.sort.join}, but extra characters were found: "
    ~ "{$charbag.kxxv}\n" if $charbag.kxxv;
  @output.sort.join;
}

View the entire Raku script for this task on GitHub.

$ raku/ch-2.raku
Example 1
Input: $str = "zroezerotwotwotwo"
Output: "00222"

Example 2
Input: $str = "sveeeinght"
Output: "78"

Example 3
Input: $str = "onenineninefive"
Output: "1599"

Example 4
Input: $str = "zeroonetwothreeeightfivesixsevenninefour"
Output: "0123456789"

Example 5
Input: $str = "ninenineninenine"
Output: "9999"

Example 6
Input: $str = "onestewv"
Output: "27"

Perl

In Perl, I wanted to use Set::Bag to give myself a delete method, but that class didn’t have a subset method to determine if one bag was a subset of another bag… so I decided to implement one by overriding Set::Bag and making a child class MyBag. I was also able to provide a constructor that takes a string and breaks it up into a list that it then uses List::MoreUtils::frequency to count how times the characters occur before passing that to Set::Bag‘s constructor, and add a kxxv method that works the way Raku’s does.

package MyBag;

use List::MoreUtils qw( frequency );
use Set::Bag;

use base qw/ Set::Bag /;

sub new($class, $str) {
  my $self = Set::Bag->new(frequency split //, $str);
  bless $self, $class;
}

sub subset($self, $other) {
  foreach my ($key, $val) (%$other) {
    # this key is not part of the bag, it's a switch; and the
    # variable defining it is scoped local to the package, so
    # I can't reference it in a child class. :(
    next if $key eq 'Set::Bag::__over_delete__';
    return 0 unless $self->{$key}
                 && $self->{$key} >= $val;
  }
  return 1;
}

sub kxxv($self) {
  map { ($_) x $self->grab($_) } $self->elements;
}

package main;

my @num_bag = (
  MyBag->new("zero"),
  MyBag->new("one"),
  MyBag->new("two"),
  MyBag->new("three"),
  MyBag->new("four"),
  MyBag->new("five"),
  MyBag->new("six"),
  MyBag->new("seven"),
  MyBag->new("eight"),
  MyBag->new("nine")
);

sub reconstructDigits($str) {
  my $charbag = MyBag->new($str);
  my @output;
  for my $digit (0,2,4,6,8,7,5,3,1,9) {

    while ( $charbag->subset($num_bag[$digit]) ) {
      push @output, $digit;
      $charbag->delete($num_bag[$digit]->grab);
    }
  }
  my $out = join "", sort @output;
  if ($charbag->kxxv) {
    die "$out, but extra characters were found: "
      . join(" ", $charbag->kxxv) . "\n";
  }
  $out;
}

View the entire Perl script for this task on GitHub.

Python

Python’s Counter type, however, had all the operations I needed.

from collections import Counter

num_bag = [
  Counter([ c for c in "zero" ]),
  Counter([ c for c in "one" ]),
  Counter([ c for c in "two" ]),
  Counter([ c for c in "three" ]),
  Counter([ c for c in "four" ]),
  Counter([ c for c in "five" ]),
  Counter([ c for c in "six" ]),
  Counter([ c for c in "seven" ]),
  Counter([ c for c in "eight" ]),
  Counter([ c for c in "nine" ])
]

def reconstruct_digits(string):
  charbag = Counter([ c for c in string ])
  output = []
  for digit in [0,2,4,6,8,7,5,3,1,9]:
    while num_bag[digit] <= charbag:
      output.append(digit)
      charbag -= num_bag[digit]
  out = "".join(map(str, sorted(output)))
  if len(charbag) > 0:
    raise ValueError(
      f'{out}, but extra characters were found: ' +
      " ".join(charbag.elements())
    )
  return out

View the entire Python script for this task on GitHub.

Elixir

Elixir, on the other hand, did not have any of the tools I needed, so I needed to roll my own subset? and delete_subset routines to take bags implemented as Maps and do the necessary operations. A map is a subset of another map if all the keys of the subset are in the other map and all the values are less than or equal to the values in the other map. Deleting a subset from a map involves subtracting the values for each key from the other map, and removing the key if the value becomes 0.

def bag(str), do: String.codepoints(str) |> Enum.frequencies()

def num_bag(digit),
  do:
    Enum.at(
      [
        bag("zero"),
        bag("one"),
        bag("two"),
        bag("three"),
        bag("four"),
        bag("five"),
        bag("six"),
        bag("seven"),
        bag("eight"),
        bag("nine")
      ],
      digit
    )

def subset?(big, small) do
  small
  |> Map.keys()
  |> Enum.reduce(true, fn key, acc ->
    acc && Map.has_key?(big, key) &&
      Map.get(big, key) >= Map.get(small, key)
  end)
end

def delete_subset(big, small) do
  small
  |> Map.keys()
  |> Enum.reduce(big, fn key, big ->
    {_, big} =
      Map.get_and_update(big, key, fn val ->
        newval = val - Map.get(small, key)
        if newval > 0, do: {val, newval}, else: :pop
      end)

    big
  end)
end

def reconstruct_digits([], output, charbag) do
  out = output |> Enum.sort() |> Enum.join()

  if charbag != %{} do
    elements =
      charbag
      |> Map.keys()
      |> Enum.reduce([], fn c, list ->
        list ++ List.duplicate(c, Map.get(charbag, c))
      end)
      |> Enum.join(" ")

    raise "#{out}, but extra characters were found: #{elements}"
  else
    out
  end
end

def reconstruct_digits([digit | remain], output, charbag) do
  nbag = num_bag(digit)

  if subset?(charbag, nbag) do
    charbag = delete_subset(charbag, nbag)
    output = output ++ [digit]
    reconstruct_digits([digit | remain], output, charbag)
  else
    reconstruct_digits(remain, output, charbag)
  end
end

def reconstruct_digits(str) do
  reconstruct_digits(
    [0, 2, 4, 6, 8, 7, 5, 3, 1, 9],
    [],
    bag(str)
  )
end

View the entire Elixir script for this task on GitHub.


Here’s all my solutions in GitHub: https://github.com/packy/perlweeklychallenge-club/tree/challenge-401-packy-anderson/challenge-401/packy-anderson

Leave a Reply