in reply to Re: Re: Finding the intersect of two ranges
in thread Finding the intersect of two ranges

Your right. Unfortunately, little diagrams on paper don't always make for good testcases. The +1 was a um...fencepost error!

1 2 3 4 5 2 3 4 5 6 1 2 3 4 <<< Range = 4 NOT!

Since when does a coder count from 1 not zero!

The idea was that if the range is negative, it has to be wrong so, no overlap. Which of course leads onto the second error.

My original tests were these.

sub overlap{ ($_[1] < $_[3] ? $_[1]: $_[3]) - ($_[0] > $_[2] ? $_[0] : $_[2]) + 1; } @data = qw[1 5 2 6]; print "\n@data : ", overlap @data and @data = map($_-1, @data) while grep $_>0,@data; 1 5 2 6 : 4 0 4 1 5 : 4 -1 3 0 4 : 4 -2 2 -1 3 : 4 -3 1 -2 2 : 4 -4 0 -3 1 : 4 my @data = qw[1 2 5 6]; print "\n@data : ", overlap @data and @data = map($_-1, @data) while grep $_>0,@data; 1 2 5 6 : -2 0 1 4 5 : -2 -1 0 3 4 : -2 -2 -1 2 3 : -2 -3 -2 1 2 : -2 -4 -3 0 1 : -2 my @data = qw[2 5 1 6]; print "\n@data : ", overlap @data and @data = map($_-1, @data) while grep $_>0,@data; 2 5 1 6 : 4 1 4 0 5 : 4 0 3 -1 4 : 4 -1 2 -2 3 : 4 -2 1 -3 2 : 4 -3 0 -4 1 : 4 my @data = qw[1 6 2 5]; print "\n@data : ", overlap @data and @data = map($_-1, @data) while grep $_>0,@data; 1 6 2 5 : 4 0 5 1 4 : 4 -1 4 0 3 : 4 -2 3 -1 2 : 4 -3 2 -2 1 : 4 -4 1 -3 0 : 4

Which I thought (wrongly) meant I'd covered all the edge cases. A bad testcse is worse than no testcase.

Here's a fixed but it's not nearly so pretty, nor efficient. It's dubious if this is any better than your original.

#! perl -slw use strict; sub overlap{ @_ = map{abs $_ } @_ if 4 == grep $_ < 0, @_; local $_ = ($_[1] < $_[3] ? $_[1]: $_[3]) - ($_[0] > $_[2] ? $_[0] + : $_[2]) ; $_ > -1 ? $_ : 0; } while(<DATA>) { chomp; print,next unless length; print $_, ' = ', overlap( ( split(' ') )[0 .. 3] ); } print''; my @data = qw[1 5 2 6]; print "@data : ", overlap @data and @data = map($_-1, @data) while grep $_>0,@data; __DATA__ 1 2 2 3 (0) 2 3 1 2 (0) 1 2 3 4 (0) 1 3 2 4 (1) 1 4 2 3 (1) 2 4 1 3 (1) 3 4 1 2 (0) -2 -1 1 2 (0) -2 1 -1 2 (2) -2 2 -1 1 (2) -1 2 -2 1 (2) 1 2 -2 -1 (0) -2 -3 -1 -2 (0) -1 -2 -3 -4 (0) -1 -3 -2 -4 (1) -1 -4 -2 -3 (1) -2 -4 -1 -3 (1) -3 -4 -1 -2 (0)
Outputs

C:\test>232325 1 2 2 3 (0) = 0 2 3 1 2 (0) = 0 1 2 3 4 (0) = 0 1 3 2 4 (1) = 1 1 4 2 3 (1) = 1 2 4 1 3 (1) = 1 3 4 1 2 (0) = 0 -2 -1 1 2 (0) = 0 -2 1 -1 2 (2) = 2 -2 2 -1 1 (2) = 2 -1 2 -2 1 (2) = 2 1 2 -2 -1 (0) = 0 -2 -3 -1 -2 (0) = 0 -1 -2 -3 -4 (0) = 0 -1 -3 -2 -4 (1) = 1 -1 -4 -2 -3 (1) = 1 -2 -4 -1 -3 (1) = 1 -3 -4 -1 -2 (0) = 0 1 5 2 6 : 3 0 4 1 5 : 3 -1 3 0 4 : 3 -2 2 -1 3 : 3 -3 1 -2 2 : 3 -4 0 -3 1 : 3 C:\test>

I think I tried all the variations this time, but as always, better minds and different eyes may see it differently.


Examine what is said, not who speaks.

The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.