[erlang-questions] Programming challenge

Matthias Lang <>
Mon Feb 18 10:28:42 CET 2008


Zvi writes:

 > So I decided to write it in Erlang. Bellow is my code. Critique is wellcome.

Why do so much work yourself? The io library can do lots for you, i.e.

  {ok, [H, M, AMPM], []} = io_lib:fread("~d:~d ~s", Time_string),

  io_lib:fwrite("~p:~2.2.0w ~s", [Hours rem 12, Minutes rem 60, AM])

I don't much like the MM1, MM2, MM3 stuff either, there's an awful lot
of shuffling going on there which obscures what's actually being done.

The original question said "The exercise isn't meant to be too
hard. We just want to see how you code". I didn't think of the problem
with wrapping from 11:59 AM to 12:01 PM (your code gets it wrong, it
wraps to 00:01 PM) until I tried some cases. 

I wonder if the "interviewers" outsmarted themselves or if they were
being nasty. Not good either way.

You also have to decide what to do for a bunch of other odd cases.  Is
five minutes after midnight 00:05 AM or is it 12:05 AM? Do you allow
negative jumps? Negative wrapping across midnight? If a user enters
14:01 PM, should we accept that? What about "9:0 AM"? Anyway, I've
spent enough time on this now. My solution is appended.

Matt

----------------------------------------------------------------------
-module(time_exercise).
-export([add_minutes/2]).

add_minutes(Time_string, Jump_minutes) ->
    {ok, [H, M, AMPM], []} = io_lib:fread("~d:~d ~s", Time_string),
    Total = time_to_minutes(H, M, AMPM) + Jump_minutes,
    minutes_to_string(Total).

time_to_minutes(Hours, Minutes, "AM") 
  when Hours < 12, Hours >= 0, Minutes < 60, Minutes >= 0 ->
    Hours * 60 + Minutes;

time_to_minutes(Hours, Minutes, "PM") 
  when Hours < 12, Hours >= 0, Minutes < 60, Minutes >= 0 ->
    (Hours + 12) * 60 + Minutes;

time_to_minutes(12, Minutes, "PM") 
  when Minutes < 60, Minutes >= 0 ->
    12 * 60 + Minutes.

minutes_to_string(Minutes) when Minutes >= 0 ->
    Hours = (Minutes div 60) rem 24,
    {A_hours, AMPM} = ampm(Hours),
    Deep = io_lib:fwrite("~p:~2.2.0w ~s", [A_hours, Minutes rem 60, AMPM]),
    lists:flatten(Deep).

ampm(12) -> {12, "PM"};
ampm(Hours) when Hours > 12 -> {Hours rem 12, "PM"};
ampm(Hours) when Hours < 12 -> {Hours, "AM"}.



More information about the erlang-questions mailing list