Daniel Lemire's blog

, 3 min read

Computing the Hamming distance between two strings in Java?

4 thoughts on “Computing the Hamming distance between two strings in Java?”

  1. Will says:

    It’s very easy to compute — it’s just the number of differences, right?

    def hamming(s1 ,s2)
    dist = 0
    Range.new(0,s1.length-1).each {|i| dist += 1 unless s1[i] == s2[i] }
    dist
    end

  2. Right.

    I got as far as this:

    int hamming (String s1, String s2) {
    if(s1.size() != s2.size()) return -1;// not sure whether there is someting better to do
    int counter = 0;
    for (int k = 0; k < s1.size();++k) if(s1.at(k) != s2.at(k)) ++counter; return counter; }

    But that's a tad ugly.

  3. Jason says:

    As ugly as it may look, that’s the standard for Java. A quick Google code search only pulls up things similar to what you have.

  4. lyrachord says:

    There is a blog:
    https://blogs.ucl.ac.uk/chime/2010/06/28/java-example-code-of-common-similarity-algorithms-used-in-data-mining/

    And the project contains other distances: http://alias-i.com/lingpipe/index.html

    Odd:) I’m tring to apply distance to compression