Lesson 1
Analyzing Social Networking App Logs Using Kotlin
Introduction

Welcome to our new coding practice lesson! We have an interesting problem in this unit that centers around data from a social networking app. The challenge involves processing logs from this app and extracting useful information from them. This task will leverage your skills in string manipulation, working with timestamps, and task subdivision. Let's get started!

Task Statement

Imagine a social networking application that allows users to form groups. Each group has a unique ID ranging from 1 to n, where n is the total number of groups. Interestingly, the app keeps track of when a group is created and deleted, logging all these actions in a string.

The task before us is to create a Kotlin function named analyzeLogs. This function will take as input a string of logs and output a List<String> representing the groups with the longest lifetime. Each string in the list contains two items separated by a space: the group ID and the group's lifetime. By 'lifetime,' we mean the duration from when the group was created until its deletion. If a group has been created and deleted multiple times, the lifetime is the total sum of those durations. If multiple groups have the same longest lifetime, the function should return all such groups in ascending order of their IDs.

For example, if we have a log string as follows: "1 create 09:00, 2 create 10:00, 1 delete 12:00, 3 create 13:00, 2 delete 15:00, 3 delete 16:00", the function will return: ["2 05:00"].

Solution Building: Step 1

First, we will split the input string into individual operations. In Kotlin, string manipulation can be handled using the split() and toList() methods.

Kotlin
1fun analyzeLogs(logs: String): List<String> { 2 val logList = logs.split(", ").toList()
Solution Building: Step 2

Next, we delve deeper into the logs. For each logged group operation in the string, we need to parse its components. These include the group ID, the type of operation (create or delete), and the time of action.

Kotlin
1fun analyzeLogs(logs: String): List<String> { 2 val logList = logs.split(", ").toList() 3 4 val timeDict = mutableMapOf<Int, Pair<Int, Int>>() // Map to record the creation moment for each group in minutes 5 val lifeDict = sortedMapOf<Int, Int>() // SortedMap to record the lifetime for each group in minutes 6 7 for (log in logList) { 8 val parts = log.split(" ") 9 val groupId = parts[0].toInt() 10 val action = parts[1] 11 val time = parts[2]
Solution Building: Step 3

Now that we can identify the action performed on each group and when, it's time to process these details. We convert the group ID into an integer and the timestamp into minutes from the start of the day. If the log entry marks a create action, we register the time of creation in a map under the group ID. If the entry signals delete, we calculate the lifetime of the group and store it in another map.

Kotlin
1fun analyzeLogs(logs: String): List<String> { 2 val logList = logs.split(", ").toList() 3 4 val timeDict = mutableMapOf<Int, Pair<Int, Int>>() // Map to record the creation moment for each group in minutes 5 val lifeDict = sortedMapOf<Int, Int>() // SortedMap to record the lifetime for each group in minutes 6 7 for (log in logList) { 8 val parts = log.split(" ") 9 val groupId = parts[0].toInt() 10 val action = parts[1] 11 val time = parts[2] 12 13 // Parsing the time from HH:MM format 14 val (hour, minute) = time.split(":").map { it.toInt() } 15 val currentTime = hour * 60 + minute // Time in minutes from start of day 16 17 if (action == "create") { 18 timeDict[groupId] = Pair(hour, minute) 19 } else { 20 timeDict[groupId]?.let { 21 // If the group is deleted, calculate its entire lifetime and remove it from the creation records. 22 val creationTime = it.first * 60 + it.second 23 val lifetime = currentTime - creationTime 24 lifeDict[groupId] = lifeDict.getOrDefault(groupId, 0) + lifetime 25 timeDict.remove(groupId) 26 } 27 } 28 }
Solution Building: Step 4

After recording the lifetimes of all groups, we can compare them to determine which group or groups had the longest lifetime. Finally, we return the ID or IDs of that group or groups, sorted in ascending order, along with their lifetime.

Kotlin
1fun analyzeLogs(logs: String): List<String> { 2 val logList = logs.split(", ").toList() 3 4 val timeDict = mutableMapOf<Int, Pair<Int, Int>>() // Map to record the creation moment for each group in minutes 5 val lifeDict = sortedMapOf<Int, Int>() // SortedMap to record the lifetime for each group in minutes 6 7 for (log in logList) { 8 val parts = log.split(" ") 9 val groupId = parts[0].toInt() 10 val action = parts[1] 11 val time = parts[2] 12 13 // Parsing the time from HH:MM format 14 val (hour, minute) = time.split(":").map { it.toInt() } 15 val currentTime = hour * 60 + minute // Time in minutes from start of day 16 17 if (action == "create") { 18 timeDict[groupId] = Pair(hour, minute) 19 } else { 20 timeDict[groupId]?.let { 21 val creationTime = it.first * 60 + it.second 22 val lifetime = currentTime - creationTime 23 lifeDict[groupId] = lifeDict.getOrDefault(groupId, 0) + lifetime 24 timeDict.remove(groupId) 25 } 26 } 27 } 28 29 // Find the longest lifetime 30 val maxLife = lifeDict.maxByOrNull { it.value }?.value ?: 0 31 32 // Building the result list where each item is a string of "group ID lifetime" if it has the longest lifetime. 33 return lifeDict.filter { it.value == maxLife } 34 .map { 35 val hours = it.value / 60 36 val minutes = it.value % 60 37 "${it.key} ${"%02d:%02d".format(hours, minutes)}" 38 } 39 .sortedBy { it.split(" ")[0].toInt() } 40} 41 42fun main() { 43 val logs = "1 create 09:00, 2 create 10:00, 1 delete 12:00, 3 create 13:00, 2 delete 15:00, 3 delete 16:00" 44 val result = analyzeLogs(logs) 45 for (entry in result) { 46 println("Group ${entry.split(" ")[0]} lifetime: ${entry.split(" ")[1]}") 47 } 48 // Outputs: 49 // Group 2 lifetime: 05:00 50}
Lesson Summary

Bravo! You have successfully navigated a non-trivial log analysis problem and worked with timestamped data, a real-world data type in Kotlin. Using Kotlin's string methods and collections, you transformed raw strings into meaningful data. Real-life coding often involves accurately understanding, dissecting, and analyzing data, and this unit's lesson has given you practical experience in that regard. Now, let's apply these new learnings to more practice challenges. Off to the races you go!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.