DEV Community

FatimaAlam1234
FatimaAlam1234

Posted on

File Question - C++

Given a text file with conversation write an algorithm which can give you list of user who chat the most

#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>
#include <algorithm>
#include <vector>

std::vector<std::string> getMostActiveUsers(const std::string& filePath) {
    std::unordered_map<std::string, int> userCounts;

    // Open the file
    std::ifstream file(filePath);
    if (!file.is_open()) {
        std::cerr << "Error: Unable to open file." << std::endl;
        return {};
    }

    // Read the file line by line
    std::string line;
    while (std::getline(file, line)) {
        // Extract user information
        std::string username = line.substr(0, line.find(':'));
        // Update user count
        userCounts[username]++;
    }

    // Close the file
    file.close();

    // Find the maximum message count
    int maxCount = 0;
    for (const auto& pair : userCounts) {
        maxCount = std::max(maxCount, pair.second);
    }

    // Collect users with maximum count
    std::vector<std::string> mostActiveUsers;
    for (const auto& pair : userCounts) {
        if (pair.second == maxCount) {
            mostActiveUsers.push_back(pair.first);
        }
    }

    return mostActiveUsers;
}

int main() {
    std::string filePath = "conversation.txt";
    std::vector<std::string> mostActiveUsers = getMostActiveUsers(filePath);

    if (mostActiveUsers.empty()) {
        std::cout << "No users found in the conversation." << std::endl;
    } else {
        std::cout << "Most active user(s): ";
        for (const std::string& user : mostActiveUsers) {
            std::cout << user << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)