Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: sum towards nearest good neighbor at either end of numerical array

by RichardK (Parson)
on Jan 02, 2014 at 12:20 UTC ( [id://1068940]=note: print w/replies, xml ) Need Help??


in reply to sum towards nearest good neighbor at either end of numerical array

How about this? It seems to do you what you want, at least for the given test data.

use v5.16; use warnings; # collapse a list my @data = (0, 3, 8, 9, 5, 2, 0, 1, 0); my $acc = 0; say join(',',@data); while (@data && $data[0] < 5) { $acc += shift @data; } $data[0] += $acc; $acc = 0; while (@data && $data[$#data] < 5) { $acc += pop @data; } $data[$#data] += $acc; say join(',',@data);

BUT, what do you want to happen if the accumulated total become more than 5? i.e if the list starts (2,2,2,7,...) should the result be (13,...) or (6,7,...) or don't you care?

  • Comment on Re: sum towards nearest good neighbor at either end of numerical array
  • Download Code

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2024-04-25 23:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found