24 Sep 2006 @ 11:43 PM 
 

Cool test for between-ness

 

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));
}
Tags Categories: .NET Coding Posted By: Dave
Last Edit: 25 Sep 2006 @ 12 01 AM

E-mailPermalink
 

Responses to this post » (3 Total)

 
  1. SourceForge Project said...
    10:23 am - September 25th, 2006

    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.

  2. Dave said...
    11:06 am - September 25th, 2006

    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

  3. Dave said...
    9:31 am - September 26th, 2006

    Its up now.

 Comment Meta:
RSS Feed for comments
TrackBack URI
 

Leave A Comment ...

 

 XHTML:
You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
\/ More Options ...
Change Theme...
  • Role »
  • Posts »
  • Comments »
Change Theme...
  • VoidVoid (Default)
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LiteLightweight
  • No Child Pages...