in reply to Averaging Elements in Array of Array

you could try something like this
for(my $i=0;$i< scalar(@aoa);$i++) {
for(my $x=0;$x < scalar($aoa$i);$x++) {
$hash{$i} = $hash{$i} + $aoa$i$x;
}
}

my @res = ();
foreach my $key (sort keys %hash) {
push(@res,(($hash{$key}) / 4));
}
If you don't know the length of the aoa then you could make the '4' in '/ 4' into a var. Or you could do a hash that has more of a struct feel to it like:
$hash{$i}{'total'} = <total of the one column of values>
$hash{$i}{'array_length'} = #

Not sure how much faster this would be than what you have, but it should be fairly fast since you only go through the array of arrays once and then compute the average once. George in NC
  • Comment on Re: Averaging Elements in Array of Array

Replies are listed 'Best First'.
Re^2: Averaging Elements in Array of Array
by ikegami (Patriarch) on Dec 27, 2008 at 01:18 UTC

    This is a slower and less readable version of what I posted 15 hours ago.

    • $aoa[$i] (in $x < scalar($aoa[$i])) is buggy. It should be @{ $aoa[$i] }
    • Your code (specifically your use of sort) fails when there are more than 10 columns in each row.
    • Why do you hardcode "4" in one place but use "scalar(@aoa)" in another? That should tell you something's wrong.
    • There's no reason to use a hash here. It's not appropriate, and it just slows things down for nothing.
    • "hash" is an awful name for a variable.
    • $x = $x + $y; can be written more concisely as $x += $y;.
    • scalar(@aoa) can be written more concisely as @aoa if the context is already scalar.
    • for (my $i=0; $i<@aoa; $i++) can be written more concisely as for my $i (0..$#aoa).

    Finally, your post formatting is buggy. Put code and other preformatted data in <c>...</c> tags.

      I apologize.. it was more of an idea than an actual peice of code. I didn't see it written anywhere in the other peices, so i thought i'd throw it out there. If someone is interested in finding the best way to parse something then it's best to see or try as many options as possible before determining what is best. The code can definately be more concise or made better and no, I wouldn't use the specific code in a program, but it would be similar. The '4' along with any other part that is not to your liking can be modified depending on the needs of the app or desire of the programmer. That's the great thing about perl... there are twenty ways to do something and twenty diff opinions on what is best...