Welcome! In today's lesson, we're going to delve into the practical application of string operations and type conversions using Scala. These concepts are essential and widely utilized in many programming scenarios. We'll examine a real-world example: time parsing. Have you ever wondered how to add a given number of seconds to a specific time? By the end of today’s session, you'll know how to calculate this using Scala. Let’s get started!
Imagine this: You receive a time formatted as a string in HH:MM:SS
, where HH
, MM
, and SS
denote the hour, minute, and second, respectively. You are also given an integer representing a number of seconds. Your task is to calculate the new time after adding the provided seconds and output the result in the HH:MM:SS
format.
For example, if the input time is 05:10:30
, and the number of seconds to add is 123
, the output should be 05:12:33
, since 123
seconds translate to 2
minutes and 3
seconds.
Take note of these points when resolving this task:
- The input time is invariably a valid time string in the
HH:MM:SS
format, withHH
ranging from 00 to 23, andMM
andSS
ranging from 00 to 59. - The output ought to be a time in the same format.
Let's go ahead and break down how to achieve this in our step-by-step solution guide.
Our initial step should involve parsing the input time string. From this string, we'll extract the hours, minutes, and seconds as integer values for further calculations. In Scala, we can utilize the split
method combined with map
to divide the string at :
and convert each substring into an integer:
Scala1val time = "12:34:56" 2val timeParts = time.split(":").map(_.toInt)
By executing this operation, we've successfully parsed the time string and converted the hours, minutes, and seconds into integers.
Now that we have the hours, minutes, and seconds in integer format, we can easily calculate the total number of seconds elapsed since the day's start. The logic is as follows:
- 1 hour comprises 3600 seconds, so multiply the number of hours by 3600.
- 1 minute comprises 60 seconds, so multiply the number of minutes by 60.
- The count of seconds remains unchanged.
Given this, we can write the following Scala code:
Scala1val secondsSinceStart = timeParts(0) * 3600 + timeParts(1) * 60 + timeParts(2)
Your function should now compute the cumulative number of seconds from the start of the day.
Now, we need to add the integer representing a number of seconds to our computed secondsSinceStart
, and also consider cases where the added seconds roll over to the next day:
Scala1val totalSeconds = (secondsSinceStart + seconds) % (24 * 3600)
The modulus operator (%
) ensures that our totalSeconds
value doesn't exceed the total number of seconds in a day (86400 seconds or 24*3600 seconds).
In this part of the task, we reverse the previous operation. We're given an integer number of seconds, and we have to convert this into a time string in the HH:MM:SS
format.
We'll perform division and modulus operations in Scala to extract the hours, minutes, and seconds:
Scala1val hours = totalSeconds / 3600 2val remainder = totalSeconds % 3600 3val minutes = remainder / 60 4val secondsLeft = remainder % 60
The final step is to assemble these values into our HH:MM:SS
format string using Scala’s f
string interpolator:
Scala1f"$hours%02d:$minutes%02d:$secondsLeft%02d"
This might look succinct, but it's quite efficient. Inside the interpolator, %02d
ensures that each time value is a 2-digit number, padding with a 0
if needed.
Let's collate all the individual steps and formulate the final function:
Scala1def solution(time: String, seconds: Int): String = { 2 val timeParts = time.split(":").map(_.toInt) 3 val secondsSinceStart = timeParts(0) * 3600 + timeParts(1) * 60 + timeParts(2) 4 val totalSeconds = (secondsSinceStart + seconds) % (24 * 3600) 5 val hours = totalSeconds / 3600 6 val remainder = totalSeconds % 3600 7 val minutes = remainder / 60 8 val secondsLeft = remainder % 60 9 f"$hours%02d:$minutes%02d:$secondsLeft%02d" 10}
And voilà! You've crafted a function that accurately calculates the new time based on the provided time and number of seconds elapsed since then.
Congratulations! You've adeptly learned how to parse a time string and utilize type conversions to calculate the number of seconds that have passed since the day began. Then you learned how to do the reverse operation: calculate the time based on the number of seconds passed since the beginning of the day. In this lesson, we've practiced essential Scala skills, including string operations, list conversions, and basic arithmetic operations on integers. Continue practicing with similar problems to reinforce your learning, and you'll soon find these tasks becoming second nature. In our upcoming sessions, more practical exercises related to this topic await. See you there, and happy coding!