How to find the most common pair of characters in a string with C++

2 Answers

0 votes
#include <iostream>
#include <string>
#include <unordered_map>

// Custom hash function for std::pair<char, char>
struct PairHash {
    std::size_t operator()(const std::pair<char, char>& p) const {
        // Combine the hash values of the two characters
        return std::hash<char>()(p.first) ^ std::hash<char>()(p.second);
    }
};

std::pair<char, char> findMostCommonPair(const std::string& str) {
    std::unordered_map<std::pair<char, char>, int, PairHash> pairFrequency;
    std::pair<char, char> mostCommonPair;
    int maxFrequency = 0;

    for (size_t i = 0; i < str.length() - 1; ++i) {
        std::pair<char, char> currentPair = {str[i], str[i + 1]};
        pairFrequency[currentPair]++;

        if (pairFrequency[currentPair] > maxFrequency) {
            maxFrequency = pairFrequency[currentPair];
            mostCommonPair = currentPair;
        }
    }
    
    std::cout << "Max frequency: " << maxFrequency << "\n";

    return mostCommonPair;
}

int main() {
    std::string str = "xzvxdeshaalzxzmdenlopxzxzxzaaqdewrzaaaapeerxzxz";

    std::pair<char, char> result = findMostCommonPair(str);

    std::cout << "The most common pair: " << result.first << result.second << "\n";
}

  
   
/* 
run:
   
Max frequency: 7
The most common pair: xz
   
*/

 



answered Nov 27, 2024 by avibootz
0 votes
#include <iostream>
#include <string>
#include <map>

std::pair<char, char> findMostCommonPair(const std::string& str) {
    std::map<std::pair<char, char>, int> charPairCounts;
    std::pair<char, char> mostCommon;
    int maxCount = 0;

    for (int i = 0; i < str.length() - 1; ++i) {
        std::pair<char, char> currentPair = std::make_pair(str[i], str[i + 1]);
        charPairCounts[currentPair]++;

        if (charPairCounts[currentPair] > maxCount) {
            maxCount = charPairCounts[currentPair];
            mostCommon = currentPair;
        }
    }
    
    std::cout << "Max count: " << maxCount << "\n";

    return mostCommon;
}

int main() {
    std::string str = "xzvxdeshaalzxzmdenlopxzxzxzaaqdewrzaaaapeerxzxz";
    
    std::pair<char, char> result = findMostCommonPair(str);

    std::cout << "The most common pair is: " << result.first << result.second << "\n";
}

  
   
/* 
run:
   
Max count: 7
The most common pair is: xz
   
*/

 



answered Nov 27, 2024 by avibootz

Related questions

...