in reply to Re^2: How to code this?
in thread How to code this?

Oh, I missed that! Something like this then:

#!/usr/lib/perl use strict; use warnings; my $kPoolSpan = 2; my %hash = ( 3 => [1 .. 2], 4 => [2 .. 2], 6 => [4 .. 5], 7 => [2 .. 6], 8 => [1 .. 3], 11 => [5 .. 10], ); my @indexes = sort {$a <=> $b} keys %hash; my @pool; while (@indexes) { my $oldPoolSize = @pool; push @pool, shift @indexes if !@pool; push @pool, shift @indexes while @indexes && $pool[0] + $kPoolSpan >= $indexes[0]; my $poolSum; my @new = @pool[$oldPoolSize .. $#pool]; for my $poolEntry (@pool) { $poolSum += $_ for @{$hash{$poolEntry}}; } print "Pool @pool sum (added @new): $poolSum\n"; shift @pool while @indexes && @pool && $pool[0] + $kPoolSpan < $in +dexes[0]; }

Prints:

Pool 3 4 sum (added 3 4): 5 Pool 4 6 sum (added 6): 11 Pool 6 7 8 sum (added 7 8): 35 Pool 11 sum (added 11): 45
True laziness is hard work

Replies are listed 'Best First'.
Re^4: How to code this? (Solved)
by BrowserUk (Patriarch) on Nov 15, 2011 at 03:40 UTC

    Thank you. With a few tweaks to deal with stuff not mentioned in the question, this is my addaption of your code:

    our $INT //= 4; my %hash; push @{ $hash{ calcScore( $_ ) } }, $_ while <>; my @grpKeys = sort{ $a <=> $b } keys %hash; my @oldGrp; while( my $next = shift @grpKeys ) { ## Remove any arrays from teh previously processed group ## that are below the interval of the next value - $INT shift @oldGrp while ( $next - $oldGrp[ 0 ] ) > $INT. ## Process items in the new array for my $i ( 0 .. $#{ $hash{ $next } } ) { ## against each of the (other) items in the new array for my $j ( $i+1 .. $#{ $hash{ $next } } ) { process( $i, $j ); } ## and all of the items in each of the arrays ## retained from the previous pass for my $g ( @oldGrp ) { for my $j ( 0 .. $#{ $hash{ $g } } ) { process( $i, $j ); } } } ## Add this array to the previously processed group push @oldGrp, $next; }

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.