perl - Subroutine that takes average of one or more arrays -
i'm working on subroutine takes average of 1 or more arrays. without using module.
use strict; use warnings; use list::util 'sum'; @w = (0, 2); @x = (1, 3); @y = (2, 2); @z = (1, 1); # average of these 4 arrays (1,2) since # (0+1+2+1)/4 = 1 , (2+3+2+1)/4 = 2 @arrays = \(@w, @x, @y, @z); @avg; # way using module $i (0..$#w) { $avg[$i] = sum(map $_->[$i], @arrays) / @arrays; } print "@avg\n"; # way of doing without module @avg; $i (0..$#w) { $avg[$i] = prod_sum(map $_->[$i], \@arrays) / @arrays; } print "@avg\n"; # subroutines sub prod_sum{ $o = $_[0]; $arr_ref = $_[1]; $array_ref; foreach $row (@$arr_ref){ foreach $cell (@$row) { push(@{ $array_ref }, $_); } } $sum = $o + the_sum($array_ref); return $sum; } sub the_sum{ $sum = 0; ( @{$_[0]} ) { $sum += $_; } return $sum; }
output
1 2 [pair of random big numbers]
the first output correct. displays average of of arrays. second output wrong. how do without using module?
i propose solution:
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)
Comments
Post a Comment