Perl Quiz, Perl Solution: Plusified Equations
Posted: September 11th, 2009 | Author: Eduard Lohmann | Filed under: Perl, Perl Quiz of the Week | No Comments »For problem definition see: The Haskell solution.
Because this was a test for an applicant, I felt I should solve it too in order to get a good idea of how difficult it is.
My approach was so generate the plussified expressions from smallest to largest sum. That way I can discard any expressions from one list that have a smaller sum then the least sum of the other list.
The Algorithm
- Generate a list of plussified expressions for each of the integers, sorted smallest to largest sum.
- Compare the sums of the first elements of both lists. If one is less then the other remove it and repeat.
-
If the sums are equal you have found an answer.
You could now drop the first expression of each list and continue,
but you would miss the answers where you link the current first element of one list with
expressions in the other list that are not first, but have the same sum.
Therefore I also explicitly look for those answers with a recursive call.
Questions welcome at eduard@tty.nl .
use strict;
use warnings;
main( @ARGV );
sub main {
/^\d+$/ or die("'$_' is not a valid string of digits.") for @_;
2 == @_ or die("Supply exactly 2 strings of digits seperated by a space");
my @answers = find_answers( [ plusify(shift) ], [ plusify(shift) ] );
print join("\n", @answers ), "\nFound " . scalar(@answers) . " answers.\n";
return;
}
sub plusify {
my ($num) = @_;
my ($first_digit, $rest) = $num =~ m/(\d)(\d+)?/;
return ($first_digit) if not defined $rest;
my @ways = map { $first_digit . $_ , $first_digit . '+' . $_ } plusify($rest);
return sort { sum_expression($a) <=> sum_expression($b) } @ways;
}
sub sum_expression {
my ($expression) = @_;
my $sum = 0;
$sum += $_ for split(qr{\+}, $expression);
return $sum;
}
sub find_answers {
my ( $expressions_1, $expressions_2 ) = @_;
my @expressions_1 = @{ $expressions_1 };
my @expressions_2 = @{ $expressions_2 };
my @answers = ();
while ( @expressions_1 and @expressions_2 ) {
my $head_1 = shift(@expressions_1);
my $head_2 = shift(@expressions_2);
my $sum_1 = sum_expression($head_1);
my $sum_2 = sum_expression($head_2);
if ( $sum_1 == $sum_2 ) {
push(@answers,"$head_1 = $sum_1 = $head_2" ) ;
push(@answers, find_answers( [ $head_1 ], [ @expressions_2 ] ) );
push(@answers, find_answers( [ @expressions_1 ], [ $head_2 ] ) );
};
# Effectively only shift the lowest of the heads
unshift(@expressions_2, $head_2) if $sum_1 < $sum_2;
unshift(@expressions_1, $head_1) if $sum_2 < $sum_1;
};
return @answers;
}
1;