http://www.perlmonks.org?node_id=521359

in reply to Obtaining terms in an expansion

It's not clear to me what you want. Maybe it's something like

```my \$C;

if (@\$ar) {
\$C = 1;
foreach my \$row (@\$arr) {
my \$sum = 0;
foreach my \$ele (@\$row) {
\$sum += \$ele;
}
\$C *= \$sum;
}
}
[download]```

By the way, you shoulnd'y use \$a and \$b as variable names to avoid conflicts with some special variables.

Update: Or maybe

```my \$cols = @{\$arr->};

my \$C;

foreach my \$col_idx (0 .. \$cols-1) {
\$C->[\$col_idx] = 1;
foreach my \$row (@\$arr) {
\$C->[\$col_idx] *= \$row->[\$col_idx];
}
}
[download]```

Replies are listed 'Best First'.
Re^2: Obtaining terms in an expansion
by randyk (Parson) on Jan 05, 2006 at 22:03 UTC
I should have supplied an example of what I was looking for. For example, for N=2:
```( arr + arr ) ( arr + arr )
[download]```
what I want to find is
```C = arr arr
C = arr arr
C = arr arr
C = arr arr
[download]```
It doesn't matter if the coefficients come out in this order, of course.

If 2^N could become m^n, then you could use a recursive solution: (Updated: cleaned up slightly!)

```#! perl -slw
use strict;

sub expand{
return @{ \$_ } if @_ == 1;
map{
my \$x = \$_;
map{ \$x * \$_ } &expand;
} @{ pop @_ };
}

my @mat = ( [ -1, 2 ], [ 3, -4 ] );
printf +("%s " x @mat ) . '= ',  map{ "[ @\$_ ] " } @mat;
print join ' ', expand( @mat );

@mat = ( [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], );
printf +("%s " x @mat ) . '= ',  map{ "[ @\$_ ] " } @mat;
print join ' ', expand( @mat );

@mat = ( [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], );
printf +("%s " x @mat ) . '= ',  map{ "[ @\$_ ] " } @mat;
print join ' ', expand( @mat );

__END__
P:\test>junk
[ -1 2 ]  [ 3 -4 ]  = -3 6 4 -8
[ 1 2 ]  [ 3 4 ]  [ 5 6 ]  = 15 30 20 40 18 36 24 48
[ 1 2 3 ]  [ 4 5 6 ]  [ 7 8 9 ]  =
28 56 84 35 70 105 42 84 126 32 64 96 40 80 120 48 96 144 36 72 108 45
+ 90 135 54 108 162
[download]```

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
I don't see an operator between arr and arr, so I presume the parenthesis mean you want to multiply.

Your description does not adequately explain what you want, particularly the (a[N-1] + a[N-1]).

Indices from your example:

```0,0 1,0
0,0 1,1
0,1 1,0
0,1 1,1
[download]```
Don't follow. They should be:
```0,0 1,0
0,0 1,1
1,0 1,0
1,1 1,1
2,0 1,0
2,1 1,1
3,0 1,0
3,1 1,1
...
[download]```
The wrong element is incrementing -- a[N-1] * a, a[N-1] * a.

Furthermore, this makes no sense. Are a and a use repeatedly throughout? If so, why not change them into constants?

Celebrate Intellectual Diversity