views:

524

answers:

2

I was given this interview question recently:

Given a 12-hour analog clock, compute in degree the smaller angle between the hour and minute hands. Be as precise as you can.

I'm wondering what's the simplest, most readable, most precise algorithm is. Solution in any language is welcome (but do explain it a bit if you think it's necessary).

A: 

I do not know if it's right, .something like this?

//m*360/60 - (h*360/24)+(m*360/(24*60)) ->
t = abs(25*m - 60*h)/4
t = min(t,360-t)
aaa
Well it can't be right if you're missing an end parenthesis :D
Wallacoloo
For `h=3`, `m=0`, I get `45`. It should be `90`.
polygenelubricants
@poly okay, I forgot regular clock is 12, not 24 hours. if you replace division by 24 with 12, you should get correct
aaa
+5  A: 

It turns out that Wikipedia does have the best answer.

// h = 1..12, m = 0..59
static double angle(int h, int m) {
    double hAngle = 0.5D * (h * 60 + m);
    double mAngle = 6 * m;
    double angle = Math.abs(hAngle - mAngle);
    angle = Math.min(angle, 360 - angle);
    return angle;
}

Basically:

  • The hour hand moves at the rate of 0.5 degrees per minute
  • The minute hand moves at the rate of of 6 degrees per minute

Problem solved.


And precision isn't a concern because the fractional part is either .0 or .5, and in the range of 0..360, all of these values are exactly representable in double.

polygenelubricants
This is not quite correct for h >= 12.
starblue
@starblue: I've clarified that it's a 12-hour analog clock.
polygenelubricants