Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Optimizing a double loop

by bart (Canon)
on Jun 03, 2010 at 14:33 UTC ( #842931=note: print w/replies, xml ) Need Help??


in reply to Optimizing a double loop

moritz's post, or rather his discussion of it on the ChatterBox, made me think, and it inspired me to come up with a related yet different solution.

My solution is based on the idea of a step function, often spelled "" in math, and adding them together (function of x, edge at t):

    (x, t) = 0 if x < t
            = 1 if x > t
            = ?? if x == t (often 1/2 in continuous math functions)
As this is about discrete values, I'd rather make that
    (x, t) = 0 if x < t
            = 1 if x > t
            = 1 if x == t (for discrete input)
That way, the added value for a range, say [20, 50], can be
    (x, 20) - (x, 51)
So, just as with moritz's solution, you can store the value for a range as 2 tuples for each edge:
%step = ( 20 => 1, 50+1 => -1 );
You can imagine this to represent a number of Dirac pulses; the combination of step functions is the integral of this set of pulses, or, because we're in the discrete case, the sum of amplitudes of every pulse on its left.

For each range you add, in the same hash, you can then increment the value for the lower edge, and decrement for the upper edge + 1.

my %step; foreach(@range) { $step{ $_->[0] }++; $step{ $_->[1]+1 }--; }
Now, the next step is to convert this data structure to the final outcome. If you need a complete data structure for the whole spectrum, you'll have to loop through the full range once, on each edge, adding the value for $step{$edge} to the previous accumulated value and assigning that to the range:
my @edge = sort { $a <=> $b } keys %step; my $step = 0; my $x = shift @edge; for(my $i = $x; defined $x; $i++) { if($i == $x) { $step += $step{$x}; $x = shift @edge; } $arr[$i] += $step; }
Tested with
@arr = (0) x 120; @range = ([20, 50], [30, 100]);
The end result of print "@arr\n"; is:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 +2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 + 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2021-10-24 20:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My first memorable Perl project was:







    Results (89 votes). Check out past polls.

    Notices?