Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest path algorithm for an analog clock

Tags:

algorithm

math

I've got a c homework problem that is doing my head in and will be greatful if anyone can help point me in the right direction.

If I have two minutes points on an analog watch such as t1 (55 minutes) and t2 (7 minutes), I need to calculate the shortest amount of steps between the two points.

What I've come up with so far is these two equations:

-t1 + t2 + 60 =
    -55 + 7 + 60 
    = 12

t1 - t2 + 60 = 
    55 - 7 + 60 
    = 108

12 is lower then 108, therefore 12 steps is the shortest distance.

This appears to work fine if I compare the two results and use the lowest. However, if I pick out another two points for example let t1 = 39 and t2 = 34 and plug them into the equation:

-t1 + t2 + 60 = -39 + 34 + 60 = 55
t1 - t2 + 60 = 39 - 34 + 60 = 35

35 is lower then 55, therefore 35 steps is the shortest distance.

However, 35 isn't the correct answer. 5 steps is the shorest distance (39 - 34 = 5).

My brain is a little fried, and I know I am missing something simple. Can anyone help?

Analog clock face

like image 852
Michael Pasqualone Avatar asked Jul 25 '26 05:07

Michael Pasqualone


1 Answers

What you want is addition and subtraction modulo 60. Check out the % operator. Make sure you handle negatives correctly.

like image 135
Edward Z. Yang Avatar answered Jul 28 '26 04:07

Edward Z. Yang