Task1
We parse the digits and find the result:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;
sub gcd{
my ($a,$b) = map{abs} @_;
($a,$b) = ($b,$a % $b) while $b;
$a
}
sub fraction_addition_subtraction{
my ($expr) = @_;
my ($num,$den) = (0,1);
while($expr =~ m{([+-]?\d+)/(\d+)}g){
my ($n,$d) = ($1,$2);
$num = $num * $d + $n * $den;
$den *= $d;
my $g = gcd($num,$den);
($num,$den) = ($num / $g,$den / $g) if $g > 1
}
"$num/$den"
}
is fraction_addition_subtraction('1/2+3/2'),'2/1','Example 1';
is fraction_addition_subtraction('-5/2-3/2'),'-4/1','Example 2';
is fraction_addition_subtraction('5/3-5/3'),'0/1','Example 3';
is fraction_addition_subtraction('10/10-1/10+2/5'),'13/10','Example 4';
is fraction_addition_subtraction('1/6+1/6+1/6'),'1/2','Example 5';
Task2
We reconstruct the digits using a mapping of steps:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More tests => 5;
my @STEPS = (
[0,'z','zero'],
[2,'w','two'],
[4,'u','four'],
[6,'x','six'],
[8,'g','eight'],
[3,'h','three'],
[5,'f','five'],
[7,'s','seven'],
[1,'o','one'],
[9,'i','nine'],
);
sub reconstruct_digits{
my ($str) = @_;
my %count;
$count{$_}++ for split '',$str;
my @times = (0) x 10;
foreach my $step(@STEPS){
my ($digit,$key,$word) = @$step;
my $n = $count{$key} or next;
$times[$digit] = $n;
$count{$_} -= $n for split '',$word;
}
join '',map{$_ x $times[$_]} 0..9
}
is reconstruct_digits('zroezerotwotwotwo'),'00222','Example 1';
is reconstruct_digits('sveeneinght'),'78','Example 2';
is reconstruct_digits('onenineninefive'),'1599','Example 3';
is reconstruct_digits('zeroonetwothreeeightfivesixsevenninefour'),
'0123456789','Example 4';
is reconstruct_digits('ninenineninenine'),'9999','Example 5';