The Clock Hands Problem

So, I am preparing for an interview and want to start out with the problem. The Clock Hands problem states “Write a function that returns the acute angle between two clock hands, with two integers for the number of hours and number of minutes.”

Let’s start thinking. Here is what I think is important to know:

  • Acute angles are angles that are smaller than 90 degrees
  • We know that you can essentially convert hours and minutes into the same unit and use the rate of change
  • 12:15 is 90 degrees
  • 12:30 is 180 degrees
  • 90/15 = 6
  • 180/30 = 6
  • 270/45 = 6
  • 360/60 = 6
  • It looks like every 90 degrees is a difference of 6

What we would want to clarify:

  • Do they mean the smaller angle when they say “acute?”

Know if my thinking is correct we can convert each to angles from 0. I’m going to use 3:30 as my first test. First I’ll convert 3 to minutes. So, I now have 15. Now, if I’m not mistaken each minute is 6 degrees. So I get, 90 for the hour and 180 for the minute. 180 – 90 = 90 degree angle. Also, to get what I think they mean by acute angle I’m always going to subtract from the bigger one (the one further ahead). There is also the case when it’s 12 as we will need to convert that to a zero. Finally, if we assume they mean that acute is the smallest angle (I can’t ask because it’s online) then whenever we exceed 180 we would need to subtract the value from 360.

So now on to my solution, I got this in C#:

using System;

namespace ClockHands
{
    class Program
    {
        static void Main(string[] args)
        {
            int hour = 0;
            int minute = 0;
            int hourInMinutes = 0;
            int hourAngle = 0;
            int minuteAngle = 0;
            int totalAngle = 0;
            Console.Write("Hour?:");
            hour = Int32.Parse(Console.ReadLine());
            if(hour == 12)
            {
                hour = 0;
            }
            Console.Write("Minute?:");
            minute = Int32.Parse(Console.ReadLine());
            hourInMinutes = hour * 5;
            hourAngle = hourInMinutes * 6;
            minuteAngle = minute * 6;
            if(hourAngle > minuteAngle)
            {
                totalAngle = hourAngle - minuteAngle;
            }
            else
            {
                totalAngle = minuteAngle - hourAngle;
            }
            if(totalAngle > 180)
            {
                totalAngle = 360 - totalAngle;
            }
            Console.WriteLine(string.Format("The angle is {0}", totalAngle));
        }
    }
}

This entry was posted on Monday, September 2nd, 2019 at 4:05 pm

Leave a Reply

Your email address will not be published. Required fields are marked *