How to check if two equal-length strings are at least 50% equal in Kotlin

1 Answer

0 votes
fun atLeastHalfEqual(s1: String, s2: String): Boolean {
    // Check equal length and non‑empty
    if (s1.isEmpty() || s1.length != s2.length) {
        return false
    }

    var matches = 0
    val len = s1.length

    // Compare character‑by‑character (Pascal semantics)
    for (i in 0 until len) {
        if (s1[i] == s2[i]) {
            matches++
        }
    }

    // matches / len ≥ 0.5  →  2 * matches ≥ len
    return matches * 2 >= len
}

fun main() {
    println(atLeastHalfEqual("abcde", "axcfz")) 

    println(
        atLeastHalfEqual(
            "javascript c# c++ c python",
            "javascript c# r c rust sql"
        )
    ) 
}



/*
run:

false
true

*/

 



answered Dec 21, 2025 by avibootz

Related questions

...