Quantcast
Channel: VBForums - CodeBank - Visual Basic 6 and earlier
Viewing all articles
Browse latest Browse all 1449

Determining when two numeric ranges overlap

$
0
0
The code below will report True if 2 ranges (x1-x2 & y1-y2) overlap. You can put the two range parameters in either ascending or descending order. The function will rearrange them to ascending order if necessary.

At the bottom of the function are the two lines that will determine whether the ranges overlap at any point. If the ranges merely 'touch' each other, partially overlap or completely overlap, the IsOverlapped function will, in any of these cases, report back True. Only one of the lines at the bottom of the function is needed. The other one needs to stay rem'ed out. Use either line according to your whim. :)

The line that starts out with "Not (. . .)" actually performs its 'deed' by determining if the ranges are not overlapping, and then reverses the result with "Not".

I can't take credit for the code. I found it on the stackoverflow site in a C forum looking for an efficient answer to this problem. I simply converted their solution to a VB format.

Both lines look pretty efficient, but my gut thinks the first line might have a little speed edge due to using mostly boolean operators, whereas, the second line uses mostly math. But the difference is probably splitting hairs.


Code:

Public Function IsOverlapped(ByVal x1 As Long, ByVal x2 As Long, _
                            ByVal y1 As Long, ByVal y2 As Long) As Boolean
Dim TmpSwap As Long

  ' the procedures below depend on both ranges being in
  ' ascending order so we have to test for that to make sure
  '
  If x1 > x2 Then
      TmpSwap = x1
      x1 = x2
      x2 = TmpSwap
  End If
 
  If y1 > y2 Then
      TmpSwap = y1
      y1 = y2
      y2 = TmpSwap
  End If

  ' either of these two lines will work
  ' I kinda think the 1st one is a wee bit faster
  '
  IsOverlapped = Not ((y1 > x2) Or (x1 > y2))
  'IsOverlapped = ((y2 - x1) * (x2 - y1)) >= 0
End Function

I've done some testing with various types of overlap and non-overlap and, so far, have not found any flaw in the two lines that determine overlap. If you find an example that provides an incorrect return I would appreciate hearing about it.

rdee

Viewing all articles
Browse latest Browse all 1449

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>