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

1 Answer

0 votes
package main

import (
    "fmt"
)

func atLeastHalfEqual(s1, s2 string) bool {
    // Check equal length and non-empty
    if len(s1) == 0 || len(s1) != len(s2) {
        return false
    }

    matches := 0

    // Compare byte-by-byte (same as Pascal's char-by-char)
    for i := 0; i < len(s1); i++ {
        if s1[i] == s2[i] {
            matches++
        }
    }

    // matches / len >= 0.5  →  2 * matches >= len
    return matches * 2 >= len(s1)
}

func main() {
    fmt.Println(atLeastHalfEqual("abcde", "axcfz")) 
    fmt.Println(atLeastHalfEqual(
        "javascript c# c++ c python",
        "javascript c# r c rust sql",
    )) 
}


/*
run:

false
true

*/

 



answered Dec 20, 2025 by avibootz
edited Dec 21, 2025 by avibootz

Related questions

...