Angle Between Hands Of A Clock

Introduction

 
In this blog, you will learn how to solve the problem of the angle between the hands of a clock. 
 

Problem Statement

 
Given two numbers, hour and minutes of an analog clock, we need to find the smallest angle (in degrees) formed between the hour and the minute hand in the analog clock. Let's illustrate the problem using an example of when the hour hand is at 12 and minutes hand is at 30, we will get the angle enclosed by 165 degrees. This is elaborated in the diagram given below:
 
Given below are some more examples for the leetcode problem:
  1. static void Main(string[] args)  
  2. {  
  3.     var result = AngleClock(12, 30);  
  4.     // example 1 : result = 165  
  5.     result = AngleClock(3, 30);  
  6.     // example 2 : result 75  
  7.     result = AngleClock(3, 15);  
  8.     // example 3 : result = 7.5  
  9.     result = AngleClock(4, 50);  
  10.     // example 4 : result = 155  
  11.     result = AngleClock(12, 0);  
  12.     // example 5 : result = 0  
  13. }  

Solution

 
We will simply use the geometric maths knowledge to evaluate the angle enclosed by the two hands. The algorithm will be as follows:
  1. Calculate the minutes hand with respect to the 0th degree of the clock in terms of radiants.
  2. Calculate the two parts of the hour's hand one clockwise with respect to the 0th degree and other anticlockwise with respect to the 0th degree.
  3. Add the two-hour hands' parts to get the hour hand angle with respect to the 0th degree.
  4. Calculate the difference between the two angles formed by the hours and the minute's hand. 
Here is the C# code for the above algorithm:
  1. public static double AngleClock(int hour, int minutes)  
  2. {  
  3.     double minAngle = minutes * 360 / 60;  
  4.     double hourAnglePart1 = 0;  
  5.     if (hour != 12)  
  6.         hourAnglePart1 = (hour * 360) / 12;  
  7.   
  8.     double hourAnglePart2 = (30 * minutes) /(double) 60;  
  9.     double hourAngle = hourAnglePart1 + hourAnglePart2;  
  10.   
  11.     double angleEnclosed = Math.Abs(minAngle - hourAngle);  
  12.     if (angleEnclosed > 180)  
  13.         angleEnclosed = 360 - angleEnclosed;  
  14.     return angleEnclosed;  
  15. }