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!
Imagine a social networking application that allows users to form groups. Each group has a unique ID ranging from 1 up to n
, 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 C++ function named analyzeLogs()
. This function will take as input a string of logs and output a vector of pairs representing the groups with the longest lifetime. Each pair contains two items: 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"}}
.
Firstly, we will split the input string into individual operations. In C++, string manipulation can be handled using functions from the string
library and streams from the sstream
library.
C++1#include <iostream> 2#include <sstream> 3#include <vector> 4#include <string> 5#include <unordered_map> 6#include <map> 7#include <algorithm> 8 9std::vector<std::pair<int, std::string>> analyzeLogs(std::string logs) { 10 std::vector<std::string> logList; 11 std::stringstream ss(logs); 12 std::string log; 13 14 // Break down the log string into individual logs by splitting 15 while (std::getline(ss, log, ',')) { 16 logList.push_back(log); 17 }
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.
C++1#include <iostream> 2#include <sstream> 3#include <vector> 4#include <string> 5#include <unordered_map> 6#include <map> 7#include <algorithm> 8 9std::vector<std::pair<int, std::string>> analyzeLogs(std::string logs) { 10 std::vector<std::string> logList; 11 std::stringstream ss(logs); 12 std::string log; 13 14 while (std::getline(ss, log, ',')) { 15 logList.push_back(log); 16 } 17 18 std::unordered_map<int, std::pair<int, int>> timeDict; // Dictionary to record the creation moment for each group in minutes 19 std::map<int, int> lifeDict; // Dictionary to record the lifetime for each group in minutes 20 21 for (const auto &log : logList) { 22 std::stringstream logStream(log); 23 int groupId; 24 std::string action, time; 25 logStream >> groupId >> action >> time;
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 dictionary under the group ID. If the entry signals delete
, we calculate the lifetime of the group and store it in another dictionary.
C++1#include <iostream> 2#include <sstream> 3#include <vector> 4#include <string> 5#include <unordered_map> 6#include <map> 7#include <algorithm> 8 9std::vector<std::pair<int, std::string>> analyzeLogs(std::string logs) { 10 std::vector<std::string> logList; 11 std::stringstream ss(logs); 12 std::string log; 13 14 while (std::getline(ss, log, ',')) { 15 logList.push_back(log); 16 } 17 18 std::unordered_map<int, std::pair<int, int>> timeDict; // Dictionary to record the creation moment for each group in minutes 19 std::map<int, int> lifeDict; // Dictionary to record the lifetime for each group in minutes 20 21 for (const auto &log : logList) { 22 std::stringstream logStream(log); 23 int groupId; 24 std::string action, time; 25 logStream >> groupId >> action >> time; 26 27 // Parsing the time from HH:MM format 28 int hour = std::stoi(time.substr(0, 2)); 29 int minute = std::stoi(time.substr(3, 2)); 30 int currentTime = hour * 60 + minute; // Time in minutes from start of day 31 32 if (action == "create") { 33 timeDict[groupId] = std::make_pair(hour, minute); // If the group is created, log the creation time. 34 } else { 35 if (timeDict.find(groupId) != timeDict.end()) { 36 // If the group is deleted, calculate its entire lifetime and remove it from the creation records. 37 int creationTime = timeDict[groupId].first * 60 + timeDict[groupId].second; 38 int lifetime = currentTime - creationTime; 39 lifeDict[groupId] += lifetime; 40 timeDict.erase(groupId); 41 } 42 } 43 }
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.
C++1#include <iostream> 2#include <sstream> 3#include <vector> 4#include <string> 5#include <unordered_map> 6#include <map> 7#include <algorithm> 8 9std::vector<std::pair<int, std::string>> analyzeLogs(std::string logs) { 10 std::vector<std::string> logList; 11 std::stringstream ss(logs); 12 std::string log; 13 14 while (std::getline(ss, log, ',')) { 15 logList.push_back(log); 16 } 17 18 std::unordered_map<int, std::pair<int, int>> timeDict; // Dictionary to record the creation moment for each group in minutes 19 std::map<int, int> lifeDict; // Dictionary to record the lifetime for each group in minutes 20 21 for (const auto &log : logList) { 22 std::stringstream logStream(log); 23 int groupId; 24 std::string action, time; 25 logStream >> groupId >> action >> time; 26 27 // Parsing the time from HH:MM format 28 int hour = std::stoi(time.substr(0, 2)); 29 int minute = std::stoi(time.substr(3, 2)); 30 int currentTime = hour * 60 + minute; // Time in minutes from start of day 31 32 if (action == "create") { 33 timeDict[groupId] = std::make_pair(hour, minute); // If the group is created, log the creation time. 34 } else { 35 if (timeDict.find(groupId) != timeDict.end()) { 36 // If the group is deleted, calculate its entire lifetime and remove it from the creation records. 37 int creationTime = timeDict[groupId].first * 60 + timeDict[groupId].second; 38 int lifetime = currentTime - creationTime; 39 lifeDict[groupId] += lifetime; 40 timeDict.erase(groupId); 41 } 42 } 43 } 44 45 // Find the longest lifetime 46 auto maxLifeIt = std::max_element(lifeDict.begin(), lifeDict.end(), [](const std::pair<int, int>& a, const std::pair<int, int>& b) { 47 return a.second < b.second; 48 }); 49 50 int maxLife = maxLifeIt->second; 51 52 // Building the result vector where each item is a pair of group ID and its lifetime if it has the longest lifetime. 53 std::vector<std::pair<int, std::string>> result; 54 for (const auto &entry : lifeDict) { 55 if (entry.second == maxLife) { 56 int hours = entry.second / 60; 57 int minutes = entry.second % 60; 58 std::string timeString = (hours < 10 ? "0" : "") + std::to_string(hours) + ":" + (minutes < 10 ? "0" : "") + std::to_string(minutes); 59 result.push_back(std::make_pair(entry.first, timeString)); 60 } 61 } 62 63 // Sorting the result in ascending order of the group IDs 64 std::sort(result.begin(), result.end()); 65 return result; 66}
Bravo! You have successfully navigated a non-trivial log analysis problem and worked with timestamped data, a real-world data type in C++. Using C++'s string and unordered_map libraries alongside traditional arithmetic, 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!