Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #365 Convert an angle to a direction

Convert a degree, x, of 360, to a Compass direction, y.

For example, `123.4 deg` is "South-east".

type
  TDir = (N, NE, E, SE, S, SW, W, NW);
const
  Dirs: array[TDir] of string = ('North','North East','East','South East','South','South West','West','North West');

var
  y: double;
  x: string;
begin
  ...
  y := Dirs[TDir(Round(((x-22.5)/45) + 0.5) mod 8)]);
end.
#include <array>
#include <string>
using namespace std;
namespace point {
    array a {
        "N", "NE", "E", "SE",
        "S", "SW", "W", "NW"
    };
    string parse(double& x) {
        double b {(x / 45) + .5};
        return a[int(b) % 8];
    }
}
string y {point::parse(a)};
char y {"NESW"[int((x / 90.) + .5) % 4]};
enum Point {
    N, NE, E, SE, S, SW, W, NW;
    static Point parse(double x) {
        int i = (int) ((x / 45) + .5);
        return values()[i % 8];
    }
}
String y = Point.parse(x).name();
int i = (int) ((x / 90.) + .5) % 4;
char y = "NESW".charAt(i);
y = 'NESW'[int((x / 90) + .5) % 4]
y = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"][int((x / 45) + 0.5) % 8]
winds = %w(N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW)
wind_count = winds.size
y = winds[ x * wind_count / 360.0 + 0.5 % wind_count ]

New implementation...
< >
reilas