I’ve been doing the Weekly
Challenges. The
latest
involved fraction arithmetic and letter unscrambling. (Note that this
ends today.)
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 given
expression in string format. If final result is an integer, change
it to the format of fraction that has a denominator 1.
For Raku, Python, Ruby and Crystal I used the built-in rational types.
I know other languages have Rational types available in external
libraries, but I prefer to use built-ins (to avoid the faff of library
management systems) or write my own (which encourages me to write more
of my own code).
In either case this is a three step procedure: parse the input string,
do the calculation, return the output string.
Perl, where I wrote my own:
sub fractionaladditionsubstraction($a) {
Set up various state-tracking variables.
my @terms;
my $state = 0;
my $n = 0;
my $num = 0;
my $sign = 0;
my @cv = split '', $a;
Iterate through the string with a state machine.
my $i = 0;
while ($i < scalar @cv) {
State zero: we aren't in a number. Determine the sign of this term if
it's given, or store a first digit.
if ($state == 0) {
if ($cv[$i] eq '+') {
$state = 0;
$i++;
} elsif ($cv[$i] ge '0' && $cv[$i] le '9') {
$sign = 1;
$state = 1;
$n = 0 + $cv[$i];
$i++;
} elsif ($cv[$i] eq '-') {
$sign = -1;
$state = 1;
$n = 0;
$i++;
}
} elsif ($state == 1) {
We are in the numerator. Append a digit, or store numerator and begin
calculating the denominator.
if ($cv[$i] ge '0' && $cv[$i] le '9') {
$n = $n * 10 + $cv[$i];
$i++;
} elsif ($cv[$i] eq '/') {
$num = $n * $sign;
$n = 0;
$state = 2;
$i++;
}
} elsif ($state == 2) {
We are in the denominator. Anything other than a digit means store
this fraction as a term and get ready for another.
if ($cv[$i] ge '0' && $cv[$i] le '9') {
$n = $n * 10 + $cv[$i];
$i++;
} else {
push @terms, Local::Rational->new($num, $n);
$state = 0;
}
}
}
If there was anything left over (which there will be), store a final
term.
if ($state == 2) {
push @terms, Local::Rational->new($num, $n);
}
Start with the first term.
my $out = $terms[0];
Add each other term (positive or negative) to it.
foreach my $nti (1 .. $#terms) {
$out->add($terms[$nti]);
}
Return the final result.
return $out->stringify();
}
That's pretty much what the parsing and calculation steps look like in
the languages with built-in rational packages too. But here's the
extra bit for Perl, a minimal fraction package:
package Local::Rational;
Library lcm and gcd functions for reduction.
sub gcd {
my ($m,$n)=@_;
while ($n!=0) {
($m,$n)=($n,$m % $n);
}
return $m;
}
sub lcm {
my ($m,$n)=@_;
return $m/gcd($m,$n)*$n;
}
Initialise, with numerator and denominator parameters (and immediately
reduce).
sub new {
my $class = shift;
my $self={
n => 1,
d => 1,
};
bless $self,$class;
if (scalar @_ == 2) {
$self->{n} = $_[0];
$self->{d} = $_[1];
}
$self->reduce;
return $self;
}
Reduce: find the gcd, if greater than 1 divide both terms by it.
sub reduce {
my $self = shift;
my $gcd = gcd($self->{n}, $self->{d});
if ($gcd > 1) {
$self->{n} /= $gcd;
$self->{d} /= $gcd;
}
}
Add: find the lcm of the denominators, scale each numerator up, add
them and reduce.
sub add {
my $self = shift;
my $other = shift;
my $lcm = lcm($self->{d}, $other->{d});
my $n = $self->{n} * $lcm / $self->{d} + $other->{n} * $lcm / $other->{d};
$self->{n} = $n;
$self->{d} = $lcm;
$self->reduce;
}
Stringify: produce numerator, "/", denominator.
sub stringify {
my $self=shift;
return join('/', $self->{n}, $self->{d});
}
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.
There is clearly possible ambiguity here, as redundant letters are
allowed. I found a partial solution, to derive an order for testing
numbers such that unique letters are tried first: the first digit
tested is 2, since only "two" contains a w. Similarly 6 for x, and 0
for z. Once those are gone, of the remaining digits only 7 contains an
"s", and so on.
There is still ambiguity even using this: for example the string
"fiveour" could be resolved as "4, and i, v, e left over" or "5, and
o, u, r left over". I suspect a "proper" solution would be a
backtracking search for a solution with minimal redundant letters, and
some sort of further comparison standard between results. But I didn't
feel like doing that.
I also lost enthusiasm for doing this without a proper counter
(multiset) class that can do subsets and subtractions. These exist in
core Raku and Python, and I've written one for PostScript. There's an
external one for Rust (counter) that I use a lot. They exist as
external libraries for Ruby and Crystal, and possibly other languages
too, but I didn't go looking.
Python:
def reconstructdigits(a):
Build a list of counters, each containing the letters of a particular
digit, and another with the letters of the input.
digits = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
cc = []
for d in range(10):
cc.append(Counter(list(digits[d])))
cs = Counter(list(a))
ol = []
Check for digits in the cunning letter-excluding order, push any
matches onto the output list, and subtract the counter for that digit
from the one for the input list.
for d in [2, 6, 0, 7, 4, 3, 5, 8, 1, 9]:
while cc[d] <= cs:
ol.append(d)
cs = cs - cc[d]
Sort and return the result.
ol.sort()
return "".join([str(x) for x in ol])
Full code in all tagged languages is on
codeberg.