Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a degree x, find the nearest degree in an array of degrees

I have an array of degrees, [10, 90, 200, 280, 355] for a circle.

I'm given a degree, let's say 1. How do I determine that 1 is closest to 355 degrees?

like image 207
jaysonp Avatar asked Aug 16 '11 00:08

jaysonp


3 Answers

Subtract the two numbers. If the difference is larger above 180 [or below -180], subtract [or add] 360. Now you can just compare absolute values of the difference.

like image 65
hmakholm left over Monica Avatar answered Nov 10 '22 10:11

hmakholm left over Monica


Here is an actual formula:

degreediff = min(abs(x-y),360-abs(x-y))
like image 26
Jacob Eggers Avatar answered Nov 10 '22 08:11

Jacob Eggers


This is more compact and efficient:

function difference(a, b) {
    var d = Math.abs(a - b);
    return d > 180 ? 360 - d : d;
};

function closest(a, bs) {
    var ds = bs.map(function(b) { return difference(a, b); });
    return bs[ds.indexOf(Math.min.apply(null, ds))];
};

> difference(1, 355)
6

> closest(1, [10, 90, 200, 280, 355])
355
like image 1
rlx Avatar answered Nov 10 '22 08:11

rlx