Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

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

2 Answers

0 votes
import kotlin.collections.HashMap

fun main() {
    val s = "xzvxdeshaalzxzmdenlopxzxzxzaaqdewrzaaaapeerxzxz"
    
    println("The most common pair: ${findMostCommonPair(s)}")
}

fun findMostCommonPair(s: String): String? {
    val pairCount = HashMap<String, Int>()
    
    for (i in 0 until s.length - 1) {
        val pair = s.substring(i, i + 2)
        pairCount[pair] = pairCount.getOrDefault(pair, 0) + 1
    }

    var mostCommonPair: String? = null
    var maxCount = 0
    for ((key, value) in pairCount) {
        if (value > maxCount) {
            mostCommonPair = key
            maxCount = value
        }
    }
    
    println("Max count: $maxCount")

    return mostCommonPair
}



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

 



answered Nov 28, 2024 by avibootz
0 votes
fun findMostCommonPair(s: String): kotlin.collections.Map.Entry<String, Int>? {
    if (s.isEmpty()) return null

    val pairCounts = s.windowed(2).groupingBy { it }.eachCount()
    
    return pairCounts.maxByOrNull { it.value }
}

fun main() {
    val s = "xzvxdeshaalzxzmdenlopxzxzxzaaqdewrzaaaapeerxzxz"

    val result = findMostCommonPair(s)

    if (result != null) {
        println("The most common pair: ${result.key} with count: ${result.value}")
    } else {
        println("No pairs found")
    }
}


 
/*
run:
   
The most common pair: xz with count: 7
   
*/

 



answered Nov 28, 2024 by avibootz
...