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

Re: Calculate overlap between 2 ranges of numbers

by Cristoforo (Deacon)
on Oct 22, 2011 at 21:50 UTC ( #933107=note: print w/replies, xml ) Need Help??

in reply to Calculate overlap between 2 ranges of numbers

The hard way. :-)

Seriously, there may be easier solutions, (Set::IntSpan).

This way involves the vec function.

#!/usr/bin/perl use strict; use warnings; use List::Util qw/ min max /; my @range = ([5,15], [2, 20]); my $min = min map {$_->[0]} @range; my $max = max map {$_->[1]} @range; my @vec = ("") x @range; for my $i (0 .. $#vec) { vec($vec[$i], $_, 1) = 1 for $range[$i][0] .. $range[$i][1]; } my $overlap = shift @vec; $overlap &= $vec[ $_ ] for 0 .. $#vec; my $count; for my $offset ($min .. $max) { ++$count if vec($overlap, $offset, 1) == 1; } print $count;
And a thank you for this solution from another post by BrowserUK.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://933107]
[chacham]: the same thing could be achieved with a trigger
[LanX]: choroba yes
chacham shudders at the thought of using a evil
LanX will need to find a Perl workaround ... :-|
LanX leaving his cave to enjoy sun! *\o/*

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2017-03-30 15:14 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (360 votes). Check out past polls.