Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to test if number falls within certain 22.5 degree range of 360 degree circle

Tags:

java

I am building a compass, and need to return a different String for the cardinal direction depending on what 22.5 degree interval the user is currently in.

For reference, please look at this picture.

Here is a sample 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 else if statements continues in 22.5 degree intervals until all cardinal directions are covered. Is there a more efficient way to do this? Currently, Android Studio/IntelliJ is giving an error message saying this method is too complex to analyze by data flow algorithm. Regardless of the error message, I think there might be a more elegant way to do this, but I can't think of it at the moment.

Any ideas? Thanks!

like image 390
pez Avatar asked Jan 09 '23 01:01

pez


1 Answers

Integer arithmetic is your friend:

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)];
}

This will work for any positive value.


If you prefer a more in-line approach:

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)];
like image 57
Bohemian Avatar answered Jan 26 '23 05:01

Bohemian