Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch style C# construct with double range cases

I'm trying to come up with the best way of doing some kind of switch style selection on a double to find out what range it is in. Something like this:

double a = 1.1;
switch(a)
{
case: (0.0, 1.6)
 return 1;
case: (1.6, 2.337)
 return 2;
case: (2.337, 3.2974)
 return 3;
default:
  return -1;
}

Obviously in this example, one value in the range would have to be non-inclusive, but you get my drift. Any Ideas?

Edit, the ranges are not necessarily integral.

EDIT 2: I'm actually dealing with radians and finding out which of 12 ranges a point is in. I ended up doing this:

double pi = Math.PI;
double[] zones = new double[] {
        0, pi/6, pi/3, pi/2,
        2*pi/3, 5*pi/6, pi, 7*pi/6,
        4*pi/3, 3*pi/2, 5*pi/3, 11*pi/6
    };

for (int i = 0; i < 11; i++)
{
    if (radians > zones[i] && radians <= zones[i + 1])
    {
        return i + 1;
    }
}

I started to do an binary search type if-else, but it was going to get too messy.

like image 731
PhilBrown Avatar asked Dec 13 '22 04:12

PhilBrown


1 Answers

The following is ideally suited to adjacent ranges, since you only need to write the range limits once:

double a = 1.1;

if (a < 0.0) {
    // Too low
    return -1;
} else if (a < 1.6) {
    // Range [0.0, 1.6)
    return 1;
} else if (a < 2.337) {
    // Range [1.6, 2.337)
    return 2;
} else if (a < 3.2974) {
    // Range [2.337, 3.2974)
    return 3;
} else {
    // Too high
    return -1;
}
like image 114
Magnus Hoff Avatar answered Dec 14 '22 18:12

Magnus Hoff