Re: Perl 'Medium' Quiz-of-the-Whatever for 2009-08-11 : Plusified Equations

Josh Narins <[email protected]> Wed, 07 Oct 2009 20:04:21 -0400
Newsgroups gmane.comp.lang.perl.qotw.discuss
Message-ID <[email protected]>
http://www.flowersofpeace.com/telephone_code.html

Since I, by default, use +, - * and / I also make sure not to divide by zer=
o :)



On Wed, Oct 7, 2009 at 1:50 PM, Jeff Yoak <[email protected]> wrote:
> Somehow I missed the original statement of the problem, but these solutio=
ns,
> perhaps with a slight mod in some cases, could be used to solve the curre=
nt
> problem at http://mathfactor.uark.edu/ . =A0As the poster of that particu=
lar
> problem, I can say that anyone who wanted to share code with a solution
> would be welcome.
>
> Cheers,
> Jeff
>
> On Oct 7, 2009, at 9:55 AM, Ronald J Kimball wrote:
>
>> Yay, the list is back. =A0Here's my solution. =A0I generate the plusifie=
d
>> expressions iteratively by doing repeated increments, treating the
>> expression itself as a binary string with '+' and '' representing 1 and =
0:
>>
>> =A0s/(.*\d)(\d.*)/my $x =3D $2; $x =3D~ tr!+!!d; "$1+$x"/e
>>
>> To be more efficient, I don't store both sets of results. =A0First, I
>> calculate and store the results for the second expression only. =A0Then,=
 I
>> generate results one at a time for the first expression, print any match=
es
>> immediately, and throw away the result. =A0This gives the correct order =
of
>> output without any sorting.
>>
>> #!perl
>>
>> use strict;
>> use warnings;
>>
>> @ARGV =3D=3D 2
>> =A0or die usage();
>>
>> foreach (@ARGV) {
>> =A0/^\d+\z/
>> =A0 or die usage();
>> }
>>
>> my %p2;
>>
>> my ($p1, $p2) =3D @ARGV;
>>
>> do {
>> =A0push @{ $p2{do_eval($p2)} }, $p2;
>> } while ($p2 =3D next_plusify($p2));
>>
>> do {
>> =A0if (my $match =3D $p2{do_eval($p1)}) {
>> =A0 print "$p1 =3D $_\n" for @$match;
>> =A0}
>> } while ($p1 =3D next_plusify($p1));
>>
>> sub next_plusify {
>> =A0my ($exp) =3D @_;
>> =A0$exp =3D~ s/(.*\d)(\d.*)/my $x =3D $2; $x =3D~ tr!+!!d; "$1+$x"/e
>> =A0 or return;
>> =A0return $exp;
>> }
>>
>> sub do_eval {
>> =A0my ($exp) =3D @_;
>> =A0$exp =3D~ s/\+0+(?=3D\d)/\+/g;
>> =A0eval $exp;
>> }
>>
>> sub usage {
>> =A0return "$0 <int> <int>\n";
>> }
>>
>> __END__
>>
>> Ronald
>
>