Cool test for between-ness

September 24, 2006 on 11:43 pm | In .NET Coding |

I traditionally hated testing for between-ness, because I had to order the endpoints. Like to determine if x was between y and z I had to make sure that y and z were arranged in the right order and then do if x < z and x > y then return true. Well I found a better way now that allows me not to care:


// tests to see if x is between y and z (inclusively)
public bool IsBetweenIncl(IComparable x, IComparable y, IComparable z)
{
  int a = x.CompareTo(y);
  int b = x.CompareTo(z);
 
  if ( (a >= 0) != (b >= 0))
     return true;
 
  return false;
}
 
// tests to see if x is between y and z (exclusively)
public bool IsBetweenExcl(IComparable x, IComparable y, IComparable z)
{
  int a = x.CompareTo(y);
  int b = x.CompareTo(z);
 
  if ((a > 0) != (b > 0) )
     return true;
 
  return false;
}

Not earth shatterning, but it’s things like this that keep me sane when I’m writing the compiler. Yes I know there are more terse ways of writing that same stuff, but this is an illustration.

Here’s the ‘production’ versions of the same code without their illustrative qualities:


 
public bool IsBetweenIncl(IComparable x, IComparable y, IComparable z)
{
  return  ( (x.CompareTo(y) >= 0) != (x.CompareTo(z) >= 0));
}
 
public bool IsBetweenExcl(IComparable x, IComparable y, IComparable z)
{
    return ((x.CompareTo(y) > 0) != (x.CompareTo(z) > 0));
}

3 Comments »

RSS feed for comments on this post. TrackBack URI

  1. I noticed you’ve been updating the code, but if I’m reading SourceForge correctly, none of your updates to RefGen have made it into that code. Do you have a timeframe for when that might happen?

    Thanks in advance.

    Comment by SourceForge Project — September 25, 2006 #

  2. Actually I’ve updated the code quite a bit, just the ObjectDataSource stuff isn’t in there yet. I didn’t want to put it in until I’d tested it some more. It looks like it is ok now, so probably in a day or two. I’ll update it here on this page as well as in refgen

    Comment by Dave — September 25, 2006 #

  3. Its up now.

    Comment by Dave — September 26, 2006 #

Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by WordPress with Pool theme design by Borja Fernandez.
Entries and comments feeds. Valid XHTML and CSS. ^Top^