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

1 Answer

0 votes
package main

import (
    "fmt"
)

func getMostCommonPair(s string) (string, int) {
    pairFrequency := make(map[string]int)
    maxPair := ""
    maxCount := 0
    size := len(s)

    for i := 0; i < size - 1; i++ {
        pair := s[i:i + 2]
        pairFrequency[pair]++
        if pairFrequency[pair] > maxCount {
            maxPair = pair
            maxCount = pairFrequency[pair]
        }
    }

    return maxPair, maxCount
}

func main() {
    str := "xzvxdeshaalzxzmdenlopxzxzxzaaqdewrzaaaapeerxzxz";
    
    pair, count := getMostCommonPair(str)
    
    fmt.Printf("The most common pair is '%s' with a count of %d\n", pair, count)
}



/*
run:

The most common pair is 'xz' with a count of 7

*/

 



answered Nov 28, 2024 by avibootz
...