 Don't ask to ask, just ask PerlMonks

### Re: Obtaining terms in an expansion

by ivancho (Hermit)
 on Jan 06, 2006 at 00:57 UTC ( #521394=note: print w/replies, xml ) Need Help??

in reply to Obtaining terms in an expansion

ok, so the 2^N terms are each a product of N terms, a[i][j], where j can be 0 or 1 and i goes from 0 to N-1
ie, each one looks like, say
a * a * a * a * ... * a[N-1]
So, we want do some binary magic.
```#!/usr/bin/perl -wl
use strict;
use Data::Dumper;

my \$N = 4;
my \$size = 32;
my \$arr = [[1, 2],
[3, 4],
[5, 6],
[7, 8]];

my @C;

foreach my \$m (0..2**\$N - 1) {

my \$vec = "";
vec(\$vec, 0, \$size) = \$m;
my @bits = split(//, unpack("B*", \$vec));
splice(@bits, 0, \$size - \$N);

# so @bits now contains the binary expansion of \$m
# with exactly \$N bits, as you can verify by uncommenting
#    print join "::", @bits;

\$C[ \$m ] = 1;
# now we multiply the \$N terms \$arr->[i][j]
# where j is the i-th bit in the binary expansion of \$m
\$C[ \$m ] *= \$arr->[ \$_ ][ \$bits[\$_] ] for 0..\$N-1;
}

print Dumper \@C;

note, \$size must be a power of 2, for vec to work, and unless you're on a 64-bit machine, it probably cannot be more than 32.

also, this works for \$N no more than 31(32?) - but you may have other problems (memory say), if you want to go above that.

Hope this helps.

Create A New User
Node Status?
node history
Node Type: note [id://521394]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (2)
As of 2021-05-12 01:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Perl 7 will be out ...

Results (124 votes). Check out past polls.

Notices?