The most effective way to check if a number falls within the range of 22.5 degrees 360 degrees

I am creating a compass, and I need to return another line for the cardinal direction, depending on which interval the user is at 22.5 degrees.

For reference, see this image.

Here is an example of my current code:

if ((azimuth >= 348.75 && azimuth <= 360) || (azimuth >= 0 && azimuth <= 11.25))
{
    return "N";
}
else if (azimuth < 348.75 && azimuth >= 326.25)
{
    return "NNW";
}

This series of operators else ifcontinues with an interval of 22.5 degrees until all the main directions are covered. Is there a more efficient way to do this? Android Studio / IntelliJ is currently giving an error message this method is too complex to analyze by data flow algorithm. Regardless of the error message, I think there may be a more elegant way to do this, but I cannot think about it at the moment.

Any ideas? Thank!

+4
5

- :

private static final POINTS = new String[]{
    "N", "NNE", "NE", "ENE", 
    "E", "ESE", "SE", "SSE",
    "S", "SSW", "SW", "WSW",
    "W", "WNW", "NW", "NNW"};

public static String point(int azimuth) {
    return POINTS[(int)((azimuth + 11.25) % 360 / 22.5)];
}

.


:

return new String[]{"N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
    "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"}
    [(int)((azimuth + 11.25) % 360 / 22.5)];
+8

javascript, :

districts = 'N;NNE;NE;ENE;E;ESE;SE;SSE;S;SSW;SW;WSW;W;WNW;NW;NNW';
districts.split(';')[Math.round(azimuth / 22.5) % 16];

16

+2

[0; 360]. . , else-if , return .

if (azimuth >= 0 && azimuth < 180) {
    if (azimuth < 90) {
        ....
    }
    else { // >= 90 and < 180
        ....
    }
}
else { // >= 180 && < 360
    ....
}
0

, azimuth [0..360]:

if (azimuth <= 11.25) return "N";
if (azimuth <= 33.75) return "NNE";
if (azimuth <= 56.25) return "NE";
if (azimuth <= 78.75) return "ENE";
...
if (azimuth <= 348.75) return "NNW";
return "N";

: .

0

I think RangeMap search is the best solution. You can find the RangeMap implementation in the Guava library.

-1
source

All Articles