473,791 Members | 3,275 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Determing whether two ranges overlap

Hey guys

I was wondering if you could give me a hand with something. If I have two
tuples that define a range, eg: (10, 20), (15, 30), I need to determine
whether the ranges overlap each other. The algo needs to catch:

(10, 20) (15, 25)
(15, 25) (10, 20)
(10, 25) (15, 20)
and
(15, 20) (10, 25)

I can think of lots of ways to do this but it's in a tight loop so I need
it to be as efficient as possible. Any help welcome :-)

Cheers

-Rob
Feb 16 '06 #1
6 19186

Robin Haswell wrote:
Hey guys

I was wondering if you could give me a hand with something. If I have two
tuples that define a range, eg: (10, 20), (15, 30), I need to determine
whether the ranges overlap each other.


def overlap(a,b):
return a[0] <= b[0] <= a[1] or b[0] <= a[0] <= b[1]

-- Paul

Feb 16 '06 #2
On Thu, 16 Feb 2006 15:22:15 +0000, Robin Haswell wrote:
Hey guys

I was wondering if you could give me a hand with something. If I have two
tuples that define a range, eg: (10, 20), (15, 30), I need to determine
whether the ranges overlap each other. The algo needs to catch:

(10, 20) (15, 25)
(15, 25) (10, 20)
(10, 25) (15, 20)
and
(15, 20) (10, 25)

What do you mean "catch"? Do you expect the algorithm to recognise these
combinations as special and return something different?

I'm going to assume that there are no magic values that need to be caught,
because I don't know what that means, and just proceed as if the task is
to compare two tuples of the form (x1, x2) where x1 <= x2.

# warning: untested!
def isoverlap((x1,x 2), (y1,y2)):
"""Given two numeric ranges, returns a flag True or False
indicating whether they overlap.

Assumes that the ranges are ordered (smallest,large st). If
that assumption is wrong, incorrect results may occur."""

# Fully overlapping cases:
# x1 <= y1 <= y2 <= x2
# y1 <= x1 <= x2 <= y2
# Partially overlapping cases:
# x1 <= y1 <= x2 <= y2
# y1 <= x1 <= y2 <= x2
# Non-overlapping cases:
# x1 <= x2 < y1 <= y2
# y1 <= y2 < x1 <= x2

return not (x2 < y1 or y2 < x1)
I can think of lots of ways to do this but it's in a tight loop so I
need it to be as efficient as possible.


"Efficient as possible" in what way? Least memory used? Smallest
number of bytes of source code? Fastest performance?

Assuming you need fastest performance, the general method to do that is to
write it in hand-tuned assembly language, taking care to use all the
tricks to optimize it for the particular CPU you are running on. If you
can find a way to push the processing into any high-end graphics
processors you might have, that typically will speed it up even more. It
is still, sometimes, possible for the best assembly programmers to just
barely outperform optimizing C compilers, or so I'm told.

If you are willing to set your sights just a little lower, and rather than
aiming for the absolute fastest code possible, settle for code which is
fast enough, the usual technique is to stick to Python. Write different
functions implementing the various methods you can think of, and then time
them with the timeit module. Pick the fastest. Is it fast enough that
performance is satisfactory? If so, then you are done.

Here is a technique that may speed your code up a little: it is quicker to
find local variables than global. So, instead of this:

def main():
... code here ...
while condition:
flag = isoverlap(t1, t2)
... code ...

you can gain a little speed by making a local reference to the function:

def main():
... code here ...
iso = isoverlap # make a local reference for speed
while condition:
flag = iso(t1, t2)
... code ...
If your code is still too slow, you might speed it up with Psycho, or you
may need to write a C extension. Either way, you won't know if the code is
fast enough until you actually run it.
--
Steven.

Feb 16 '06 #3
Robin Haswell wrote:
I was wondering if you could give me a hand with something. If I have two
tuples that define a range, eg: (10, 20), (15, 30), I need to determine
whether the ranges overlap each other. The algo needs to catch:

(10, 20) (15, 25)
(15, 25) (10, 20)
(10, 25) (15, 20)
and
(15, 20) (10, 25)

I can think of lots of ways to do this but it's in a tight loop so I need
it to be as efficient as possible. Any help welcome :-)


how about:

def overlap(a, b):
return a[1] > b[0] and a[0] < b[1]

</F>

Feb 16 '06 #4
Thanks guys, you've all been very helpful :-)

-Rob
Feb 17 '06 #5
Robin Haswell wrote:
I can think of lots of ways to do this but it's in a tight loop so I need
it to be as efficient as possible. Any help welcome :-)


There are 24 possibilities of having 4 numbers in a row, and
the following 6 of them describe nonempty intervals (the remaining
18 are obtained by reversing the endpoints of one or both
intervals, thereby making them empty):

# separate
a0 a1 b0 b1
b0 b1 a0 a1

# inside
a0 b0 b1 a1
b0 a0 a1 b1

# cross
a0 b0 a1 b1
b0 a0 b1 a1

The simplest is to exclude the first pair, i.e.

not (a1<b0 or b1<a0)

which simplifies to
a1>=b0 and b1>=a0, given by Fredrik without proof ;-)

You will have to decide whether you want ">" or ">="
(beware of the former when using floats).

If you cannot assume that the pairs are in order, this
will break.

Ralf
Feb 17 '06 #6
Fredrik Lundh wrote:
def overlap(a, b):
return a[1] > b[0] and a[0] < b[1]


Assuming that x[1] can't be smaller than x[0], this
is the right way to compare two ranges. Well, I guess
you need to figure out the borderline cases. Is it
a[1] > b[0] or a[1] >= b[0] which is relevant?

Anyway, if we have N ranges and N is big, we'll get
lots of comparisions: N*(N-1)/2.

For large values of N, it might be better to somehow
cache/aggregate the intervals if this makes it possible
to make this into an N*M comparision where M is smaller
than (N-1)/2....

E.g, with discrete values for the intervals such as with
(10, 15), one might consider something like (untested):

hits = sets.Set()

for interval in intervals:
for i in range(interval[0], interval[1]+1):
if i in hits:
raise ValueError('%s overlaps previous interval.'
% interval)
hits.add(i)

E.g. if we have 1000 intervals where the average size of
an interval is 10, you get 10000 "i in hits" and "hits.add(i )"
instead of 499500 'a[1] > b[0] and a[0] < b[1]'.

As always, it's good to measure...assum ing you have fairly
realistic data to test with.
Feb 22 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1725
by: Ben O'Steen | last post by:
Scenario: ========= Using PyGame in particular, I am trying to write an application that will run a scripted timeline of events, eg at 5.5 seconds, play xxx.mp3 and put the image of a ball on screen, at 7.8 seconds move the ball up and down. At this point, I hear you say 'Oh, like Flash'. Yes, well... Like Flash, but I don't want to take this app in the same direction as Macromedia took Flash, nor do I (ever) want the two to be
1
1692
by: Jim Di Griz | last post by:
Hi I have a problem to create an XSD that prevents overlapping ranges. Sample XML: <root> <element LowerLimit="1" UpperLimit="50000"> ..... </element>
2
3068
by: Manish Soni | last post by:
I am loading an assembly using reflection. Then I get all the methods in all types. I want to check whether a method is "unsafe". The MethodInfo class does not seem to provide this information. How can I get the info? Thanks and Regards Manish Soni
3
7659
by: Robert W. | last post by:
Long ago I developed a simple algorithm for calculating how much space is required to display a multi-line label in a limited width. It seemed to be working okay but then my testing revealed a flaw when trying to display the following string with an MS Sans Serif 8 point font in a 208 pixel width space: "A $50-million investment in cycling infrastructure - the largest history of the province" Using the Graphics "MeasureString"...
67
7711
by: PC Datasheet | last post by:
Transaction data is given with date ranges: Beginning End 4/1/06 4/4/06 4/7/06 4/11/06 4/14/06 4/17/06 4/18/06 4/21/06 426/06 4/30/06 I am looking for suggestions on how to find the date ranges where there were no transactions.
14
2937
by: nishit.gupta | last post by:
Is their any single fuction available in C++ that can determine that a string contains a numeric value. The value cabn be in hex, int, float. i.e. "1256" , "123.566" , "0xffff" , It can also contain zero
2
4722
by: anoweb | last post by:
I have two ranges of numbers and I need to determine if they overlap or adjacent and if so return a new range containing the values. The values are low and high for each pair, such that the first value of the tuple is always less than or equal to the second value in the tuple. for example: a = (0, 5) b = (5, 10)
3
1529
by: Snedker | last post by:
Hi there, I really need some input of how to approach my little assignment. A customer wants to exclude all US IP-ranges from accessing part of his website. From http://www.ipaddresslocation.org/ I've collected about 16,000 ranges in the format 208.202.120.0 208.203.111.255 208.203.114.0 208.203.244.127
7
10271
by: guido | last post by:
Hi, I'm looking for a container class that can map whole ranges of keys to objects - something like std::map, but not only for individual values for the key, but for whole ranges. Example: I want to be able to tell the container to return object a for every given key between 0 and 10, object c for every key between 11 and 500000 and object c for every key between 500001 and 599999, without having to
0
9669
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9517
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10156
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9997
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9030
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
2
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.