RogerBW's Blog

The Weekly Challenge 401: Fractional Reconstruction 29 November 2026

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.

Add A Comment

Your Name
Your Email
Your Comment

Note that I will only approve comments that relate to the blog post itself, not ones that relate only to previous comments. This is to ensure that the blog remains outside the scope of the UK's Online Safety Act (2023).

Your submission will be ignored if any field is left blank, but your email address will not be displayed. Comments will be processed through markdown.

Search
Archive
Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 2300ad 3d printing action advent of code adventure aeronautics aikakirja anecdote animation anime army astronomy audio audio tech aviation base commerce battletech bayern beer boardgaming book of the week bookmonth chain of command children chris chronicle church of no redeeming virtues cold war comedy computing contemporary cornish smuggler cosmic encounter coup covid-19 crime crystal cthulhu eternal cycling dead of winter disaster doctor who documentary drama driving drone ecchi economics en garde espionage essen 2015 essen 2016 essen 2017 essen 2018 essen 2019 essen 2022 essen 2023 essen 2024 essen 2025 essen 2026 existential risk falklands war fandom fanfic fantasy feminism filk film firefly first world war flash point flight simulation food garmin drive gazebo genesys geocaching geodata gin gkp gurps gurps 101 gus harpoon historical history horror horrorm science fiction hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2021 hugo 2022 hugo 2023 hugo 2024 hugo 2025 hugo 2026 hugo-nebula reread humour in brief avoid instrumented life javascript julian simpson julie enfield kickstarter kotlin learn to play leaving earth linux liquor lovecraftiana lua mecha men with beards mpd museum music mystery naval noir non-fiction one for the brow openscad opera parody paul temple perl perl weekly challenge photography podcast poetry politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant review reviews romance rpg a day rpgs ruby rust scala science fiction scythe second world war security shipwreck simutrans smartphone south atlantic war squaddies stationery steampunk stuarts suburbia superheroes suspense talon television the resistance the weekly challenge thirsty meeples thriller tin soldier torg toys trailers travel traveller type 26 type 31 type 45 typst vietnam war war wargaming weather wives and sweethearts writing about writing x-wing young adult
Special All book reviews, All film reviews
Produced by aikakirja v0.1