Sunday, October 17, 2004

Finding the angle between two clock hands

I've 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. using System; public class ClockProblem {
    public float FindAngleBetweenHands(int hour, int minute) {
      float minuteHandAngle, hourHandAngle, angle; //If it's 12 hour consider it 0 if(hour == 12) hour = 0; //Whole clock face has 360 degrees and hence for each minute, //the minute hand must move 6 degrees in clockwise direction minuteHandAngle = minute * 6; //A hour hand moves 30 degrees in an hour. //Hence (hour * 30) gives us the number of degrees it moves. //Also, the hour hand must move 0-30 degrees in accordance with //the number of minutes the minute hand is showing. //the hour hand moves 0.5f degrees per minute. Adjust hour angle accordingly. hourHandAngle = (hour * 30) + (minute * 0.5f) ; angle = Math.Abs(hourHandAngle - minuteHandAngle); //The degrees must always be within 180 degrees meaning //3:00 & 9:00 PM both show 90 degrees. if(angle > 180)
        angle = 360 - angle;
      return angle;
    } public static void Main(string [] args) {
      if(args.Length != 1) {
        Console.WriteLine("Usage: ClockProblem 12:00"); return;
      } string [] time = args[0].Split(':'); int hr = Convert.ToInt32(time[0]); int min = Convert.ToInt32(time[1]); ClockProblem clock = new ClockProblem(); System.Console.WriteLine("Angle between two hands at hour {0} min {1} is {2}", time[0], time[1], clock.FindAngleBetweenHands(hr, min));
    }
}

1 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 :)