The Weekly Challenge 401

Fractional Addition Substraction & Reconstruct Digits

Official Challenge • My Solutions on GitHub

Task 1: Fractional Addition Substraction

You are given a string representing an expression of fraction addition and substraction. Write a script that returns the calculation result of the given expression in string format. If the final result is an integer, represent it as a fraction with denominator 1.

Examples

Input: $expr = "1/2+3/2" => Output: "2/1" Input: $expr = "-5/2-3/2" => Output: "-4/1" Input: $expr = "5/3-5/3" => Output: "0/1" Input: $expr = "10/10-1/10+2/5" => Output: "13/10" Input: $expr = "1/6+1/6+1/6" => Output: "1/2"

Algorithm & Approach

We scan the expression for signed fraction tokens ([+-]?\d+)/(\d+) and accumulate the running sum starting from 0/1:

Runs in O(N) time where N is the length of the expression, and O(1) extra space.

Perl Solution

#!/usr/bin/env perl
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(Str);
use Test::More;

sub _gcd ( $a, $b ) {
    $a = abs $a;
    $b = abs $b;
    while ( $b != 0 ) {
        ( $a, $b ) = ( $b, $a % $b );
    }
    return $a;
}

signature_for fraction_addition => (
    method     => 0,
    positional => [Str],
);

sub fraction_addition ($expr) {
    my $num = 0;
    my $den = 1;

    while ( $expr =~ m/([+-]?\d+)\/(\d+)/msg ) {
        my ( $n, $d ) = ( int($1), int($2) );
        $num = $num * $d + $n * $den;
        $den = $den * $d;
        my $g = _gcd( $num, $den );
        $num /= $g;
        $den /= $g;
    }

    return "$num/$den";
}

Python Solution

#!/usr/bin/env python3
"""Fractional Addition Substraction - Perl Weekly Challenge 401, Task 1."""

from __future__ import annotations

import math
import re
import unittest

_FRACTION_RE = re.compile(r"([+-]?\d+)/(\d+)")


def fraction_addition(expr: str) -> str:
    """Evaluate a fraction addition/subtraction expression and return reduced 'num/den'."""
    num = 0
    den = 1

    for match in _FRACTION_RE.finditer(expr):
        n = int(match.group(1))
        d = int(match.group(2))
        num = num * d + n * den
        den *= d
        g = math.gcd(abs(num), den)
        num //= g
        den //= g

    return f"{num}/{den}"

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.

Examples

Input: $str = "zroezerotwotwotwo" => Output: "00222" Input: $str = "sveeeinght" => Output: "78" Input: $str = "onenineninefive" => Output: "1599" Input: $str = "zeroonetwothreeeightfivesixsevenninefour" => Output: "0123456789" Input: $str = "ninenineninenine" => Output: "9999"

Algorithm & Approach

Each English digit word has a unique identifying character once earlier digits are accounted for:

Runs in O(N) time and O(1) extra space.

Perl Solution

#!/usr/bin/env perl
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(Str);
use Test::More;

signature_for reconstruct_digits => (
    method     => 0,
    positional => [Str],
);

sub reconstruct_digits ($str) {
    my %freq;
    for my $ch ( split //msx, $str ) {
        $freq{$ch}++;
    }

    my @count = (0) x 10;
    $count[0] = $freq{'z'} // 0;
    $count[2] = $freq{'w'} // 0;
    $count[4] = $freq{'u'} // 0;
    $count[6] = $freq{'x'} // 0;
    $count[8] = $freq{'g'} // 0;

    $count[1] = ( $freq{'o'} // 0 ) - $count[0] - $count[2] - $count[4];
    $count[3] = ( $freq{'h'} // 0 ) - $count[8];
    $count[5] = ( $freq{'f'} // 0 ) - $count[4];
    $count[7] = ( $freq{'s'} // 0 ) - $count[6];
    $count[9] = ( $freq{'i'} // 0 ) - $count[5] - $count[6] - $count[8];

    my $result = q{};
    for my $digit ( 0 .. 9 ) {
        $result .= "$digit" x $count[$digit];
    }

    return $result;
}

Python Solution

#!/usr/bin/env python3
"""Reconstruct Digits - Perl Weekly Challenge 401, Task 2."""

from __future__ import annotations

from collections import Counter
import unittest


def reconstruct_digits(text: str) -> str:
    """Reconstruct digits 0-9 in ascending order from scrambled English digit words."""
    freq = Counter(text)
    count = [0] * 10

    count[0] = freq["z"]
    count[2] = freq["w"]
    count[4] = freq["u"]
    count[6] = freq["x"]
    count[8] = freq["g"]

    count[1] = freq["o"] - count[0] - count[2] - count[4]
    count[3] = freq["h"] - count[8]
    count[5] = freq["f"] - count[4]
    count[7] = freq["s"] - count[6]
    count[9] = freq["i"] - count[5] - count[6] - count[8]

    return "".join(str(digit) * count[digit] for digit in range(10))