XP is just a number PerlMonks

### (Golf) Multiply polynomials

by tilly (Archbishop)
 on May 07, 2001 at 17:56 UTC Need Help??

Well I have participated in enough golf tournaments, time for me to open one.

We can represent a polynomial P by an anonymous array of its coefficients, with the i'th coefficient corresponding to the x**i term. For instance:

```[2,3]; # Represents (3x + 2)
Write a function M, that in as few characters as possible takes a list of polynomials and calculates a polynomial that is the product of the list. If called twice, it must return 2 different polynomials.

PS I am just a ref on this one.

Replies are listed 'Best First'.
Re: (Golf) Multiply polynomials
by Masem (Monsignor) on May 07, 2001 at 18:45 UTC
Here's a first shot, 110 characters in body only -- lacks some error check (it's going to fail with anything less than two arguements), but if you consider the second arg to be 0, then that makes sense.. :-)
```use strict;

my @poly1 = ( 2, 4, 6 );
my @poly2 = ( 3, 1, 0 );
my @poly4 = ( 5, 2, 1, 2 );

my @poly3 = p( \@poly1, \@poly2, \@poly4 );

print (join',',@poly3)."\n";

my @poly5 = p( \@poly4, \@poly1, \@poly2 );
print (join',',@poly5)."\n";

sub p {
my\$a=shift;my\$b=shift;my(@c,\$i,\$j);for\$i(0..\$#\$a){for\$j(0..\$#\$b){\$c[
+\$i+\$j]+=\$\$a[\$i]*\$\$b[\$j]}};@_?p(\@c,@_):\@c
}

Update: Cut down 5 more characters to 105, since you don't need to have \$j around in the inner loop:

```sub p {
my\$a=shift;my\$b=shift;my(@c,\$i);for\$i(0..\$#\$a){for(0..\$#\$b){\$c[\$i+\$_
+]+=\$\$a[\$i]*\$\$b[\$_]}};@_?p(\@c,@_):\@c
}

Update #2 as per tilly's reply, fixed the return problem to add that extra character.

Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
This can be trimmed down to 90 chars:
```  my(\$a,\$b,@r,\$c)=@_;for my\$i(0..\$#\$a){\$\$c[\$i+\$_]+=\$\$a[\$i]*\$\$b[\$_]for
+0..\$#\$b}@r?p(\$c,@r):\$c
```   MeowChow
s aamecha.s a..a\u\$&owag.print```
(Posted at MeowChow's request.)

My best is 77:

```sub p{
@m=1;for\$p(@_){my@t;for\$i(0..@m){my\$j;\$t[\$i+\$j++]+=\$_*\$m[\$i]for@\$p}@m=
+@t}[@m]
}
Note that this introduces 0's through a fencepost error, but they don't change which polynomial is represented. I think this is fair, but if you think that is cheating, you can not save that character:
```sub p{
@m=1;for\$p(@_){my@t;for\$i(0..\$#m){my\$j;\$t[\$i+\$j++]+=\$_*\$m[\$i]for@\$p}@m
+=@t}[@m]
}
The trick lies in finding ways to not work through explicit lookups by index, and in finding ways to not access arrays through references. In fact there is not a single lookup by index of an element in an array reference. (It was cheaper to create and manually increment the index variable.)

BTW note that the statement of the rules anticipated and forbade saving a character by ending with \@m without making @m a private variable.

Finally at a request from chatter, here is the solution broken out and commented:

```sub p{
@m=1;                       # Start the product at 1.
for\$p(@_){                  # Loop over the polynomials.
my@t;                     # Create a private temp array.
for\$i(0..@m){             # Loop over the indexes of @m.
my\$j;                   # Create the *other* index var.
\$t[\$i+\$j++]+=           # Manually increment \$j while..
# Adding to the index of @t..
\$_*\$m[\$i]             # 2 terms multiplied together..
for@\$p              # for all the terms in the..
}                         # other polynomial.
@m=@t                     # Make the temp array our new
}                           # product.
[@m]                        # Return our answer in the
}                             # desired form.

UPDATE
Never say you are done, 2 more characters:

```sub p{
@m=1;for\$p(@_){my@t;for\$i(0..@m){\$j=\$i;\$t[\$j++]+=\$_*\$m[\$i]for@\$p}@m=@t
+}[@m]
}

UPDATE 2
(This is a couple of days later.) Truly never say never, there were 2 more wasted characters to 73:

```sub p{
@m=1;for\$p(@_){\$i=my@t;for\$,(@m){\$j=\$i++;\$t[\$j++]+=\$_*\$,for@\$p}@m=@t}[
+@m]
}
Problem clarification.

By "return a polynomial" I mean return one in the given representation, ie it should be an anonymous array. So you need to change the last @c for \@c. (Makes this 110 characters.) The rule about different polynomials means that if you call this twice, the second answer should be a reference to a different array than the first.

New approach, but still 102. I don't I can break it any more...
```sub p {
my(\$a,\$b)=(shift,shift);
my@c=map{my(\$d,\$e);for\$e(0..\$_){\$d+=\$\$a[\$e]*\$\$b[\$_-\$e]}\$d}0..\$#\$a+\$#
+\$b;
@_?p(\@c,@_):\@c
}

Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain

Simple improvement:

```my(\$a,\$b)=(shift,shift);
my\$a=shift;my\$b=shift; # a bit shorter
my\$a=pop;my\$b=pop; # even shorter since multiplaction is commutative

- tye (but my friends call me "Tye")
Re: (Golf) Multiply polynomials
by jeroenes (Priest) on May 11, 2001 at 13:30 UTC
I know it's a tad late, but here is my \$0.01. To my opinion PDL is neglected around here, and I know I use it too little myself.

With the help of PDL I only use 43 chars for the sub, and if I looked right, it's a record in this thread. You may add 8 chars if you want to account for the extra 'use PDL;' statement:

```use PDL:
sub p{\$t=pdl+pop;\$t=\$t*(pdl\$_)for@_;[list\$t]}
This doesn't work with arrays of unequal length, but that wasn't in the spec. The output:
```print join " ", @{p([1..5],[1..5])};
1 4 9 16 25
BTW, tilly, why did you name it 'polynomials'? Isn't it just a breed of recursive vector multiplication? Do I miss something?

And, 'strictness' requires only 3 extra chars with a total of 46/54 chars (54 still is the record):

```sub p{my \$t=pdl+pop;\$t=\$t*(pdl\$_)for@_;[list\$t]}
Jeroen
"We are not alone"(FZ) Update Thx to tye I now know why tilly talked about polynomials. Sorry. If we still want a matrix-kind solution, it would be like:
```A = p1'*p2;
product = crossdiags(A);
But that's difficult to code in PDL, unfortunately. Here is my 2nd attempt, works only if poly's are equal length (pathetic 164 chars):
```sub p{\$t=pdl+pop;for(@_){
my \$a=outer\$t,pdl+pop;
transpose(\$a);
my \$n=-1+nelem\$t;
\$t=zeroes(\$n*2+1);
\$t->slice("\$_:".(\$_+\$n))+=\$a->slice("\$_,:")for 0..\$n;
}
[list\$t]}
Will ponder it a bit more and get back....

Sorry, wrong problem.

p([1..5],[1..5]) should produce [qw(1 4 10 20 35 44 46 40 25)] because ( 1 + 2x + 3x^2 + 4x^3 + 5x^4 ) * ( 1 + 2x + 3x^2 + 4x^3 + 5x^4 ) is equal to 1 + 4x + 10x^2 + 20x^3 + 35x^4 + 44x^5 + 46x^6 + 40x^7 + 25x^8 where ^ is exponentiation (** in Perl), not bit-wise XOR.

- tye (but my friends call me "Tye")

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://78498]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2022-08-14 03:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found

Notices?