Saturday, October 16, 2004

Finding the angle between two clock hands

 

I had come across an URL couple of days back: http://www.karrels.org/Ed/ACM/ec97/prob_2.html where this problem of finding the angle between two clock hands was mentioned. I wrote the following C# code yesterday. This seems to work (at least for the test inputs posted on the page). Do let me know if there's a bug.

    1 using System;

    2 

    3 public class ClockProblem

    4 {

    5     #region Public Methods

    6 

    7     public static void Main(string[] args)

    8     {

    9         if (args.Length != 1)

   10         {

   11             Console.WriteLine("Usage: ClockProblem 12:00");

   12             return;

   13         }

   14         string[] time = args[0].Split(':');

   15         var hr = Convert.ToInt32(time[0]);

   16         var min = Convert.ToInt32(time[1]);

   17         var clock = new ClockProblem();

   18         Console.WriteLine(

   19             "Angle between two hands at hour {0} min {1} is {2}",

   20             time[0],

   21             time[1],

   22             clock.FindAngleBetweenHands(hr, min)

   23         );

   24     }

   25 

   26     public float FindAngleBetweenHands(int hour, int minute)

   27     {

   28         float minuteHandAngle, hourHandAngle, angle;

   29 

   30         //If it's 12 hour consider it 0 if(hour == 12) hour = 0;

   31         //Whole clock face has 360 degrees and hence for each minute,

   32         //the minute hand must move 6 degrees in clockwise direction

   33         minuteHandAngle = minute * 6;

   34 

   35         //A hour hand moves 30 degrees in an hour.

   36         //Hence (hour * 30) gives us the number of degrees it moves.

   37         //Also, the hour hand must move 0-30 degrees in accordance with

   38         //the number of minutes the minute hand is showing.

   39         //the hour hand moves 0.5f degrees per minute.

   40         //Adjust hour angle accordingly.

   41         hourHandAngle = (hour * 30) + (minute * 0.5f) ;

   42         angle = Math.Abs(hourHandAngle - minuteHandAngle);

   43 

   44         //The degrees must always be within 180 degrees meaning

   45         //3:00 & 9:00 PM both show 90 degrees. if(angle > 180)

   46         angle = 360 - angle;

   47         return angle;

   48     }

   49 

   50     #endregion

   51 }

2 comments:

SJ said...

hi buddy, Just tatw i wld msg I saw ur Blog immediately afetr u told me where it was. take alook at mine. BTW I have translated ur program into Java :)

younus saleem saifullah said...

hi,
I used the below in C. I am unaware of C# features.

degrees = abs((30 * Hours) - (5.5 * Minutes));