Arsalan’s Musings

Musings on Software…

Time Math Interview Problem (C# Solution)

with 4 comments

This is a solution for the problem posted by Ali Abbas Rizvi here. Command line arguments are method name (e.g. AddMinutes), start time (e.g. 9:24AM), and minutes to add (e.g. 18). The result will be the new time after addminutes in the same time format.


using System;
using System.Text.RegularExpressions;
using System.Collections.Specialized;

namespace SolvingSmallProblems
{
    class Program
    {
        static void Main(string[] args)
        {
            TimeConversions timeConv = new TimeConversions();

            string commandName;
            string baseTime;
            string incrementalTime;
            string output;
            if (args.GetLength(0) == 3)
            {
                commandName = args[0];
                baseTime = args[1];
                incrementalTime = args[2];

                switch (commandName.ToUpper())
                {

                    case ("ADDMINUTES"):
                        output = timeConv.AddMinutes(baseTime, Int32.Parse(incrementalTime));
                        Console.Out.WriteLine(output);
                        Console.Out.Flush();
                        break;
                }
            }
            else
            {
                throw new Exception("Incorrect number of arguments: 2 expected...");
            }

        }      

    }

    class TimeConversions
    {
        private StringCollection meridiemValidValues;
        public StringCollection methodsAvailable;

        public TimeConversions()
        {
            meridiemValidValues = new StringCollection();
            meridiemValidValues.Add("AM");
            meridiemValidValues.Add("PM");

            methodsAvailable = new StringCollection();
            methodsAvailable.Add("AddMinutes");
        }

        public string AddMinutes(string time, int minutesToAdd)
        {
            long convertedTime = ConvertTimeToMinutes(time);
            string finalTime = ConvertMinutesToTime(convertedTime + minutesToAdd);
            return finalTime;
        }

        private string ConvertMinutesToTime(long minutes)
        {
            long calculatingHours;
            long calculatingMinutes;
            string calculatingMeridiem;

            calculatingMinutes = minutes % 60;
            // Rolling over hours for a 24-hour clock
            calculatingHours = (minutes / 60) % 24;

            if (calculatingHours < 12)
            {
                calculatingMeridiem = "AM";
                // 0 am should be written as 12 am
                if (calculatingHours == 0)
                {
                    calculatingHours = 12;
                }
            }
            else
            {
                calculatingMeridiem = "PM";
                calculatingHours -= 12;
            }

            return calculatingHours.ToString() + ":" + calculatingMinutes.ToString().PadLeft(2, '0') +
                " " + calculatingMeridiem;
        }

        private long ConvertTimeToMinutes(string time)
        {
            long normalizedTime;
            string regexStringForTimeConversion = @"^(?<Hours>[\d]{1,2}):(?<minutes>\d\d)[\s]?(?<meridiem>[AP]M)$";
            Regex regexForTimeConversion = new Regex(regexStringForTimeConversion);

            Match matchedTime = regexForTimeConversion.Match(time);
            int hours, minutes;
            string meridiem;
            try
            {
                hours = Int32.Parse(matchedTime.Groups["Hours"].Value);
            }
            catch (Exception)
            {
                throw new Exception("Invalid characters in Hours!");
            }
            try
            {
                minutes = Int32.Parse(matchedTime.Groups["Minutes"].Value);
            }
            catch (Exception)
            {
                throw new Exception("Invalid characters in Minutes!");
            }
            if (meridiemValidValues.Contains( matchedTime.Groups["Meridiem"].Value))
            {
                meridiem = matchedTime.Groups["Meridiem"].Value;
            }
            else
            {
                throw new Exception("Invalid characters in Meridiem!");
            }

            // Rule: 12 PM will be 12 in a 24-hour clock, 12 AM will be 0
            if ((hours == 12) && (meridiem == "AM"))
            {
                hours = 0;
            }
            else if ((hours < 12) && (meridiem == "PM"))
            {
                hours += 12;
            }

            normalizedTime = (hours * 60) + minutes;

            return normalizedTime;

        }

    }
}

Written by Arsalan

January 2, 2008 at 4:20 am

Posted in Code

4 Responses

Subscribe to comments with RSS.

  1. Very neat – i like the colors

    h

    January 1, 2008 at 10:33 pm

  2. Cool! This way to display the code is mighty nice.
    Did you use a wordpress plugin? May be share with us in a separate blog entry how you embedded the code here.

    imsaar

    January 4, 2008 at 2:00 pm

  3. Did you fix the bug that I also had when adding large amount of minutes?

    imsaar

    January 4, 2008 at 2:01 pm

  4. Yes, the bug should be fixed. Try it out and let me know how it went.

    Arsalan

    January 5, 2008 at 7:34 am


Leave a Reply