perl - Taking the average of many N sized arrays -
can me fix this? i'm trying write script takes sum of many n sized arrays. in example below average of arrays (1,2) since (0+1+2+1)/4 = 1 , (2+3+2+1)/4 = 2. code below works arrays of size 2. how arrays of size 100 such length of @results 100? imagine need counter right?
use strict; use warnings; @w = (0, 2); @x = (1, 3); @y = (2, 2); @z = (1, 1); @arrays = \(@w, @x, @y, @z); ($x, $y) = (0, 0); foreach $arr(@arrays) { $x += $arr->[0]; $y += $arr->[1]; } @result = ( $x / @arrays, $y / @arrays); print "@result\n"; # <---- prints 1 2 ####### # attempt @avg; $i(0..$w) { # i'm guessing result 'map...' returns array @avg[$i] = sum(\(map $_->[$i], @arrays)) / @arrays; } # sum elements in array , return value sub sum{ # takes 1 param: arrey_ref $sum = 0; ( @{$_[0]} ) { $sum += $_; } return $sum; } my attempt close doesn't work. without using module.
this solution:
use strict; use warnings; $size = 3; @w = (0, 2, 3); @x = (1, 3, 4); @y = (2, 2, 6); @z = (1, 1, 3); @arrays = \(@w, @x, @y, @z); @result = (); foreach $arr(@arrays) { for(my $i=0; $i<$size; $i++) { $result[$i] += $arr->[$i]; } } @result = map { $_ / @arrays } @result; print "(@result)", "\n"; # <---- prints (1 2 4)
Comments
Post a Comment