Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re^2: Optimizing a double loop

by roibrodo (Sexton)
on Jun 03, 2010 at 12:40 UTC ( #842905=note: print w/replies, xml ) Need Help??


in reply to Re: Optimizing a double loop
in thread Optimizing a double loop

Interesting idea. The thing is once I finished processing all the ranges, I must output the full array of counts (this is passed to another program which I don't have control on). This means I will have to translate this representation to an explicit full array with count in each cell.

Replies are listed 'Best First'.
Re^3: Optimizing a double loop
by moritz (Cardinal) on Jun 03, 2010 at 12:44 UTC
    You can still generate the full array of counts afterwards and have a speed benefit, because you only have to iterate once over the big array (as opposed to once per overlap in your current implementation).

    Update:

    Example code for obtaining the full array:

    use strict; use warnings; my @a = (10, 15, -20, -30); my $highest = abs($a[-1]); my @full = (0) x ($highest + 1); # decrement all negative values by 1, otherwise # we would exclude the end points: for (@a) { $_-- if $_ < 0; } my $count = 0; for (0..$highest) { if (abs $a[0] == $_) { my $c = shift @a; if ($c > 0) { $count++; } else { $count--; } } $full[$_] += $count; } print join('', @full), "\n";

    This assumes that there are never two values of same magnitude in the array, ie never exactly matching start- and endpoints. You can generalize it on your own :-)

    Second update: I've just realized that the extension is very simple:

    Instead of if (abs $a[0] == $_) write while (abs $a[0] == $_), and you're done.

      I'll give it a try. BTW, I will also need to sort the array (by abs values) now.

      UPDATE: There's no real to use $full[$_] += $count; instead of $full[$_] = $count;, is there? we can therefore also drop the initialization of @full, can't we?

        You're right on both accounts.

        I just used += because from reading your initial question I wasn't sure if you needed absolute values, or add them to an existing array.

Re^3: Optimizing a double loop
by ww (Archbishop) on Jun 03, 2010 at 12:44 UTC
    That does revise the spec, doesn't it?

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (1)
As of 2021-10-22 02:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My first memorable Perl project was:







    Results (85 votes). Check out past polls.

    Notices?