| 27 November 2026 | Challenge 401 |
Scrambled Fractions
Task 1: Fractional Addition Substraction
Submitted by: Mohammad Sajid Anwar
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
Solution
Perl
After laundering, we may just eval the expression under use bigrat and extract numerator and denominator.
use strict;
use warnings;
use experimental 'signatures';
use bigrat;
sub frac_add_sub ($expr) {
$expr =~ m{^(-?(?:\d+/\d+(?:[-+]|$))+)$} or return;
my $r = eval $1;
$r->numerator . '/' . $r->denominator;
}
See the full solution to task 1.
J
Evaluating the expression in J requires a few more steps for several reasons:
- Numeric operations require numeric arguments and string operations require string arguments, i.e. we need to convert from string to numeric and back.
- Rationals are represented as e.g.
3r10instead of3/10. - The negative sign is represented as
_ - Expressions are evaluated right to left.
For the latter consider the expression 4 - 1 + 2. The usual interpretation is (4 - 1) + 2 = 5.
In J it is 4 - (1 + 2) = 1.
To get the result from left-to-right interpretation, the signs may be tied to the number they precede and the sum be taken over all items.
For a summation the evaluation order is not significant:
(4 + (-1)) + 2 equals 4 + ((-1) + 2).
Here is an interactive session performing all the steps to the final result.
Replace /,-,+ with r,_, :
expr =: '10/10-17/10+2/5'
]tmp =: ('/';'r';'-';'_';'+';' ') stringreplace expr
10r10_17r10 2r5
Split at strings representing a rational:
]tmp =: '\d+r\d+' (] rxcut~ rxmatches) tmp
┌┬─────┬─┬─────┬─┬───┐
││10r10│_│17r10│ │2r5│
└┴─────┴─┴─────┴─┴───┘
Arrange as a n x 2 array:
]tmp =: _ 2 $ tmp
┌─┬─────┐
│ │10r10│
├─┼─────┤
│_│17r10│
├─┼─────┤
│ │2r5 │
└─┴─────┘
Join rows:
]tmp =: ;"1 tmp
10r10
_17r10
2r5
Convert strings to rationals:
]tmp =: 0 ". tmp
1 _17r10 2r5
Sum over all numbers:
]tmp =: +/ tmp
_3r10
Split into numerator and denominator:
]tmp =: 2 x: tmp
_3 10
Convert to boxed strings:
]tmp =: 0 <@":"0 tmp
┌──┬──┐
│_3│10│
└──┴──┘
Join with /:
]tmp =: '/' joinstring tmp
_3/10
Replace _ with -:
('_';'-') stringreplace tmp
-3/10
Everything in one verb:
frac_add_sub =: '\d+r\d+'&(('_';'-') stringreplace '/' joinstring 0 (<@":"0) 2 x: [: +/ @: (0&".) @: (;"1) (_ 2) $ ] rxcut~ [ rxmatches ])@(('/';'r';'-';'_';'+';' ')&stringreplace)
frac_add_sub '10/10-17/10+2/5'
-3/10
Task 2: Reconstruct Digits
Submitted by: Mohammad Sajid Anwar
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 = "sveeneinght"
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.
Solution
This is a very interesting task that had some twists before a final solution was found.
At first I’ll present two solutions that - although not reproducing all examples - solve a particular interpretation of the task and illustrate the path leading to the final solution.
Anagrams
My first interpretation of the task was to search for anagrams of the digit words as substrings. To this end I generated a regular expression that would match any such anagram.
The generated regex matches substrings having the length of a digit word and consisting of its characters only. Then it checks if all characters are present in the required quantity.
Repeatedly matching and removing anagrams would solve the task. The last matching capture group’s number is the matched digit plus one.
The generated regex looks like:
$words = qr{
(?^ux:([zero]{4})(?(?{$+ !~ m{(?=[^z]*+z)(?=[^e]*+e)(?=[^o]*+o)(?=[^r]*+r)}})(*FAIL))|
([one]{3})(?(?{$+ !~ m{(?=[^e]*+e)(?=[^o]*+o)(?=[^n]*+n)}})(*FAIL))|
([two]{3})(?(?{$+ !~ m{(?=[^t]*+t)(?=[^w]*+w)(?=[^o]*+o)}})(*FAIL))|
([three]{5})(?(?{$+ !~ m{(?=[^t]*+t)(?=[^h]*+h)(?=[^e]*+e[^e]*+e)(?=[^r]*+r)}})(*FAIL))|
([four]{4})(?(?{$+ !~ m{(?=[^f]*+f)(?=[^r]*+r)(?=[^o]*+o)(?=[^u]*+u)}})(*FAIL))|
([five]{4})(?(?{$+ !~ m{(?=[^v]*+v)(?=[^f]*+f)(?=[^i]*+i)(?=[^e]*+e)}})(*FAIL))|
([six]{3})(?(?{$+ !~ m{(?=[^s]*+s)(?=[^i]*+i)(?=[^x]*+x)}})(*FAIL))|
([seven]{5})(?(?{$+ !~ m{(?=[^e]*+e[^e]*+e)(?=[^n]*+n)(?=[^v]*+v)(?=[^s]*+s)}})(*FAIL))|
([eight]{5})(?(?{$+ !~ m{(?=[^t]*+t)(?=[^h]*+h)(?=[^g]*+g)(?=[^i]*+i)(?=[^e]*+e)}})(*FAIL))|
([nine]{4})(?(?{$+ !~ m{(?=[^i]*+i)(?=[^n]*+n[^n]*+n)(?=[^e]*+e)}})(*FAIL)))
}x;
and the solution is:
use strict;
use warnings;
use List::Util 'pairmap';
use List::MoreUtils 'frequency';
use List::Gather;
use experimental 'signatures';
use constant WORDS =>
qw(zero one two three four five six seven eight nine);
sub gen_w ($w) {
my $l = length $w;
"([$w]{$l})(?(?{\$+ !~ m{" .
join('', pairmap {
"(?=" . "[^$a]*+$a" x $b . ")"
} frequency split //, $w) .
"}})(*FAIL))";
}
sub reconstruct_digits_1 ($str) {
state $ws = join "|\n", map gen_w($_), WORDS;
state $words;
$words || eval "\$words = qr{$ws}x; 1;" || die $@;
join '', sort +gather {
take $#{-} - 1 while $str =~ s/$words//;
};
}
This solution fails at example 2 because the input string does’t contain a substring that is an anagram of any digit. I hadn’t expected this from the task’s wording.
Distributed Characters
Apparently a digit word does not have to be a contiguous anagram in the string.
So let’s regard input string and digit words as multi-sets of characters. Then remove as many digit multi-sets from the input multi-set as possible. The solution becomes:
use strict;
use warnings;
use Set::Bag;
use experimental 'signatures';
use constant WORDS =>
qw(zero one two three four five six seven eight nine);
sub str2bag {
Set::Bag->new(map +($_, 1), split //, shift);
}
sub reconstruct_digits_2 ($str) {
state $words = [map str2bag($_), WORDS];
my $bag = str2bag($str);
my $r = '';
while (my ($i, $word) = each @$words) {
my $diff;
# try to pick $word
while (eval {$diff = $bag - $word; 1}) {
$r .= $i;
$bag = $diff;
}
}
$r;
}
Though this solution reproduces example 2, it fails at example 4 returning 01113356.
Picking three 1’s and two 3’s from the string (surprisingly this is possible) removes the characters that would be needed to spell 2, 4, 7, 8 and 9.
I hadn’t taken this into account, neither.
Integer Linear Program
Let’s take a closer look at the constraints imposed in this task, independently from any objective.
Consider the digit words \(w = (w_j) = (\text{"one"},\ldots,\text{"nine"})\) and the characters \(c = (c_i) = (\text{'e'},\text{'f'},\text{'g'},\text{'h'},\text{'i'},\text{'n'},\text{'o'},\text{'r'},\text{'s'},\text{'t'},\text{'u'},\text{'v'},\text{'w'},\text{'x'},\text{'z'})\).
We construct a matrix \(A = (a_{ij})\) where \(a_{ij}\) is the frequency of the character \(c_i\) in the word \(w_j\).
Given a string \(s\), we find the frequency of the character \(c_i\) in \(s\) as \(b_i\).
Picking \(x_j\) instances of the digit word \(w_j\) requires \(a_{ij}x_j\) instances of the character \(c_i\). Therefore \(\sum_{j=1}^{10} a_{ij} x_j \le b_i\) must hold for every \(i\), \(1 \le i \le 15\).
Now expressing an objective:
Let’s pick as many digits as possible from the string \(s\).
Thereby we arrive at an Integer Linear Program:
\[\begin{align*} &\text{maximize:}&\sum_{j=1}^{10} x_j \\ &\text{subject to:}&\sum_{j=1}^{10} a_{ij} x_j &\le b_i &&\text{ for } 1 \le i \le 15 \\ &&0&\le x_j,\ x_j \in \Bbb{Z} &&\text{ for } 1 \le j \le 10 \\ \end{align*}\]The constraint matrix \(A\) is a constant and can be calculated from the digit words. It is:
[
[1 1 0 2 0 1 0 2 1 1]
[0 0 0 0 1 1 0 0 0 0]
[0 0 0 0 0 0 0 0 1 0]
[0 0 0 1 0 0 0 0 1 0]
[0 0 0 0 0 1 1 0 1 1]
[0 1 0 0 0 0 0 1 0 2]
[1 1 1 0 1 0 0 0 0 0]
[1 0 0 1 1 0 0 0 0 0]
[0 0 0 0 0 0 1 1 0 0]
[0 0 1 1 0 0 0 0 1 0]
[0 0 0 0 1 0 0 0 0 0]
[0 0 0 0 0 1 0 1 0 0]
[0 0 1 0 0 0 0 0 0 0]
[0 0 0 0 0 0 1 0 0 0]
[1 0 0 0 0 0 0 0 0 0]
]
The ILP can be solved using the GNU Linear Programming Kit. A couple of years ago I wrote a PDL wrapper for GLPK that comes handy here.
As GLPK uses a sparse coefficients matrix internally,
the matrix $a is converted into CCS format beforehand to avoid repeated conversions.
use strict;
use warnings;
use PDL;
use PDL::NiceSlice;
use PDL::Char;
use PDL::Opt::GLPK;
use PDL::CCS::Nd;
use experimental 'signatures';
use constant WORDS =>
qw(zero one two three four five six seven eight nine);
sub reconstruct_digits_3 ($str) {
state $words = PDL::Char->new(WORDS);
# drop \0:
state $chars = do {my $tmp = $words->uniq; $tmp->where($tmp)};
# constraint coefficients
state $a = long($words == $chars->(*1,*1))->sumover->toccs;
state $c = ones long, $a->dim(0);
state $lb = zeroes $c; # lower bounds: zero
state $ub = (2**31 - 1) * ones $c; # upper bounds: no limit
state $ctype = GLP_UP * ones long, $a->dim(1); # constraint types: <=
state $vtype = GLP_IV * ones $c; # variable types: int
# constraint rhs
my $b = long(PDL::Char->new($str) == $chars->(*1))->sumover;
glpk($c, $a, $b, $lb, $ub, $ctype, $vtype, GLP_MAX,
my $xopt = null, null, my $status = null);
die "GLPK failed" unless $status == GLP_OPT;
# repeat digit according to solution
join '', map $_->[1] x $_->[0],
cat($xopt, sequence($xopt))->xchg(0, 1)->unpdl->@*;
}
This solution reproduces all examples and it picks the digits 2789 from xenowtingsetheinev,
more than the preliminary solutions:
$ perl/ch-2.pl -t
1..2
ok 1 - skip examples
# Subtest: tests
1..1
ok 1 - make a choice: ("xenowtingsetheinev") -> 2789 {
1..3
not ok 1 - anagrams # TODO preliminary #1
# Failed test (with amnesty) 'anagrams'
# at perl/ch-2.pl line 167.
# +------+-----+----+-------+
# | PATH | GOT | OP | CHECK |
# +------+-----+----+-------+
# | [0] | 1 | eq | 2789 |
# +------+-----+----+-------+
not ok 2 - distributed chars # TODO preliminary #2
# Failed test (with amnesty) 'distributed chars'
# at perl/ch-2.pl line 172.
# +------+-----+----+-------+
# | PATH | GOT | OP | CHECK |
# +------+-----+----+-------+
# | [0] | 168 | eq | 2789 |
# +------+-----+----+-------+
ok 3 - ILP
}
ok 2 - Subtest: tests
See the full solutions to task 2 all-in-one.