Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How does one find the total (sum) of an array? 8

Status
Not open for further replies.

rdyoll

Technical User
Aug 11, 2003
39
0
0
US
Hi, let's say I have:

@numbers = qw/34 56 78 83 23 99 10/;

How can I find the "sum" of all the elements in the array?

I've tried pushing a "+" (plus sign) into the array and adding it up that way, but there has to be a better way.

The total is 383, but, I don't know the routine to follow to calculate this properly. Anyone?
 
Well, you can make a simple for() loop, or use something like List::Util's sum function.

________________________________________
Andrew - Perl Monkey
 
@numbers = qw/34 56 78 83 23 99 10/;

foreach (@numbers) {
$total += $_;
}

print "the total is: $total"


Kind Regards
Duncan
 
I have to say, looking at the list::util module, rather poor list of utils. I can think of many more statistics like average, modulus, first quarter, third quarter, etc.
 
It's just a set of simple list utilities, not a statistical analysis tool. There's a reduce() function that will let you implement whatever other functionality you want. Feel free to contact the author about adding in other features. For boolean list operations, there's also List::Utils.

________________________________________
Andrew - Perl Monkey
 
i think i hate Coderifous ;-)


Kind Regards
Duncan
 
--jim

Sickeningly simplistic, yet beautiful. -Art of coding

--Paul
 
So, give him a star then - stingy buggers :). Guess I'll have to do it. Nice work, welcome back. Haven't seen your name here for a while.
 
i'm not giving him a star... he might overtake me on the MVP ;-)

... oh, o.k. then!


Kind Regards
Duncan
 
Here I come dunc, watch out! And Paul - ever the quoter of quotable quotes. raklet, thanks for being the leader of the pack, you'd think stars were a rare commodity around here or something. ;)

--jim
 
This isn't the easiest way but I find this an interesting question, so here's what I'd do..

my $total = 0;
foreach(@numbers)
{
$total = $total + $_;
}
 
cgimonk gets the award for most-like-dunc's-code-without-being-verbatim-but-still-really-exactly-the-same.

cgimonk: the form

$x += $y

is the short form of:

$x = $x + $y

just as

$x++

is the short form of:

$x = $x + 1

--jim
 
You want the fastest way? My guess is it's like this:
Code:
my $total = 0;
$total += $_ for(@numbers);
Why? Jim's method might be neat, but evals tend to be slow. It still loops over the array with join(), but that's an internal loop, so it might be more optimized than a Perl for(). I'd still think that eval's overhead more than makes up for any gain. If it's a huge list of numbers where the loop might make a difference, the huge built up string can double your memory consumption.

Saying [tt]$total = $total + $_[/tt] is slower than [tt]$total += $_[/tt] because it has to look up [tt]$total[/tt]'s memory location twice (assuming Perl's compiler optimizes +=, which I'm sure they do. Anyone's who's touched assembly can see why this is).

And using a for loop (there's no semantic difference between for and foreach), when you give it a block of code to execute in { }, Perl has to create that structure of a block, scoping checks, etc. Using it as a statement modifier doesn't go through that overhead, but it's only useful for single statements (or anything that can be reduced to one).

Oh, and that List::Util I mentioned? If that were C-optimized, it'd win, hands down, but it's done in Perl. Not just that, using it is a subroutine call, expensive. What does the sum() function do internally? It makes a call to reduce(), another sub. That's probably the slowest of the lot.

Now, I haven't done any benchmarking, but I doubt there's much difference between them. Every little bit helps, though. Six stars for taking the sum of a list? jeez...

________________________________________
Andrew - Perl Monkey
 
Oh, I understand the syntax completely. I write code how I like to see it and what is faster for me. Typing the extra characters is faster for me to type and faster for me to read and know exactly what it's doing.
 
Six stars for an easy task? Why not seven? I like irony, so I'll give you one for that dissertation on semantics and your wholly correct assessment on eval's evils... it is slower - .76 seconds user-time over a 3 element array 10,000 times. That's versus something like .07 seconds using the += approach in a for loop.

--jim
 
I'm curious what happens if it's a million-plus length array. The eval string will eat more memory, but you might save enough overhead with join's C-optimized looping. Doubt it, but maybe. Runtime malloc will probably eat into those potential gains, too. While you're testing... ;-)

________________________________________
Andrew - Perl Monkey
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top