Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: simultaneously adding and multiplying numbers in a hash/ array

by AnomalousMonk (Abbot)
on Aug 09, 2010 at 22:12 UTC ( #853926=note: print w/ replies, xml ) Need Help??


in reply to simultaneously adding and multiplying numbers in a hash/ array

The use of a hash in this application is positively dangerous unless the elements of the  @change array (which become the keys of the hash) can be guaranteed to be unique. E.g.:

>perl -wMstrict -le "my @change = (1.15, -0.1, 5.4, 1.03, 1.15, -0.241); my @numberofshares = (9999, 400, 200, 300, 500, 240); my %hash; @hash{@change} = @numberofshares; printf qq{%d keys in hash (oops...) \n}, scalar keys %hash; my $sum = 0; while (my($k, $v) = each %hash) { $sum += $v * $k; } print qq{sum == $sum (?)}; " 5 keys in hash (oops...) sum == 1866.16 (?)

Update: The algorithm can be expressed more concisely with some list-processing functions:

>perl -wMstrict -le "use List::Util qw(sum); use List::MoreUtils qw(pairwise); use vars qw($a $b); my @change = (1.15, -0.1, 5.4, 1.03, -0.241); my @numberofshares = ( 100, 400, 200, 300, 240); my $sum = sum pairwise { $a * $b } @change, @numberofshares; print qq{sum == $sum}; " sum == 1406.16

I think it could be expressed yet more concisely in Perl 6, but my 6-fu is not that great. Would it be something like:
    my $sum +=<<*<< @change, @numberofshares;


Comment on Re: simultaneously adding and multiplying numbers in a hash/ array
Select or Download Code
Replies are listed 'Best First'.
Re^2: simultaneously adding and multiplying numbers in a hash/ array
by snoopy (Deacon) on Aug 10, 2010 at 03:17 UTC
    >> I think it could be expressed yet more concisely in Perl 6

    I like:

    say [+] @change <<*>> @numberofshares

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://853926]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2015-07-08 00:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (93 votes), past polls