Perl: the Markov chain saw PerlMonks

### Re: how to loop through many arrays

by Marshall (Canon)
 on Jun 19, 2011 at 05:24 UTC Need Help??

in reply to how to loop through many arrays

I think you are looking for the maximum of each column?
Perl operates easiest on rows. So one way to do this is to transpose the 2-D array, i.e. make the columns become rows. Here is how to do that...

Update: updated code to do what I think op is asking for..used wind's row code with List::Util::reduce() for a transposed "column".

```#!/usr/bin/perl -w
use strict;
use List::Util qw(reduce max);

my @array1=(1,2,3,4,8);
my @array2=(1,4,2,4,5);
my @array3=(1,6,1,7,5);

my @AoA = (\@array1,\@array2,\@array3);
my @transposed;

print "Original array:\n";
printAoA(\@AoA);

## tranpose array to make it easy to do column operations
##   i.e. columns become rows

foreach my \$rowref (@AoA)
{
my \$i=0;
foreach my \$num (@\$rowref)
{
push @{\$transposed[\$i++]}, \$num;
}
}

##  Now @transposed is an array of references to what used to be
##    columns.

print "\nMaximum of each column...\n".
"coordinates based on row 0..n, col 0..n\n";
my \$col=0;
foreach my \$colref (@transposed)
{
## you could have a loop: foreach my \$num (@\$colref) {} here
## below is wind's use of reduce to get the column position of
## the first maximum, perhaps you have something different in
## mind?

my \$max_pos = reduce {\$colref->[\$b] > \$colref->[\$a] ? \$b : \$a} (0.
+.@\$colref-1);
print "Max of column index \$col is \$colref->[\$max_pos] at array in
+dex \$max_pos\n";
\$col++;
}

print "\nTransposed array:\n";
printAoA(\@transposed);

sub printAoA
{
my \$refAoA = shift;
foreach my \$rowref (@\$refAoA)
{
print join(",",@\$rowref),"\n";
}
}
__END__
Original array:
1,2,3,4,8
1,4,2,4,5
1,6,1,7,5

Maximum of each column...
coordinates based on row 0..n, col 0..n
Max of column index 0 is 1 at array index 0
Max of column index 1 is 6 at array index 2
Max of column index 2 is 3 at array index 0
Max of column index 3 is 7 at array index 2
Max of column index 4 is 8 at array index 0

Transposed array:
1,1,1
2,4,6
3,2,1
4,4,7
8,5,5

Replies are listed 'Best First'.
Re^2: how to loop through many arrays
by david_lyon (Sexton) on Jun 19, 2011 at 06:42 UTC

This is incredible, thanks so much!

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2024-02-26 11:19 GMT
Voting Booth?
My favourite way to spend a leap day ...

Results (25 votes). Check out past polls.