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; } }

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->[0]}; my $C; foreach my $col_idx (0 .. $cols-1) { $C->[$col_idx] = 1; foreach my $row (@$arr) { $C->[$col_idx] *= $row->[$col_idx]; } }

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[0][0] + arr[0][1] ) ( arr[1][0] + arr[1][1] )
    what I want to find is
    C[0] = arr[0][0] arr[1][0] C[1] = arr[0][0] arr[1][1] C[2] = arr[0][1] arr[1][0] C[3] = arr[0][1] arr[1][1]
    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 @{ $_[0] } 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

      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[0][0] and arr[1][0], so I presume the parenthesis mean you want to multiply.

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

      Indices from your example:

      0,0 1,0 0,0 1,1 0,1 1,0 0,1 1,1
      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 ...
      The wrong element is incrementing -- a[0][N-1] * a[1][0], a[0][N-1] * a[1][1].

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

      Celebrate Intellectual Diversity