|
| 1 | +defmodule HackerRank.W1.TimeConversion do |
| 2 | + @moduledoc """ |
| 3 | + Time Conversion – Challenge 3 – Week 1 |
| 4 | + <https://www.hackerrank.com/challenges/three-month-preparation-kit-time-conversion/problem> |
| 5 | + """ |
| 6 | + |
| 7 | + @doc """ |
| 8 | + Converts 12-hour AM/PM time format to 24-hour military time. |
| 9 | +
|
| 10 | + ## Examples |
| 11 | +
|
| 12 | + iex> challenge("07:05:45PM") |
| 13 | + "19:05:45" |
| 14 | +
|
| 15 | + ## Constraints |
| 16 | +
|
| 17 | + - Input format: `"hh:mm:ssAM"` or `"hh:mm:ssPM"` |
| 18 | + - Always returns a string in 24-hour format |
| 19 | + """ |
| 20 | + @spec challenge(String.t()) :: String.t() |
| 21 | + def challenge(s) do |
| 22 | + # Dates / Times are not Elixis strong suit |
| 23 | + # However, binary string pattern matching is so let's do that then |
| 24 | + [hh, mm, ss_am_pm] = String.split(s, ":") |
| 25 | + |
| 26 | + # now we need am / pm |
| 27 | + <<ss::binary-size(2), period::binary>> = ss_am_pm |
| 28 | + |
| 29 | + # now parse into the correct types |
| 30 | + hour = parse_hour(hh, period) |
| 31 | + minute = String.to_integer(mm) |
| 32 | + second = String.to_integer(ss) |
| 33 | + |
| 34 | + # run everything through pad and return with Enum.map_join |
| 35 | + Enum.map_join([hour, minute, second], ":", &pad2/1) |
| 36 | + end |
| 37 | + |
| 38 | + defp parse_hour("12", "AM"), do: 0 |
| 39 | + defp parse_hour(h, "AM"), do: String.to_integer(h) |
| 40 | + defp parse_hour("12", "PM"), do: 12 |
| 41 | + defp parse_hour(h, "PM"), do: String.to_integer(h) + 12 |
| 42 | + |
| 43 | + defp pad2(number) do |
| 44 | + :io_lib.format("~2..0B", [number]) |> to_string() |
| 45 | + end |
| 46 | +end |
0 commit comments