The Hamming Distance Implementation in Javascript


The Hamming Distance is the number of different symbols between two strings/numbers (equal length). It can be also considered as the number of changes required to convert from one input to another.

If the inputs are integers, we can write a quick implementation in Javascript like this:

const hamming_distance = (a, b) => {
    let d = 0;
    let h = a ^ b;
    while (h > 0) {
        d ++;
        h &= h - 1;
    }
    return d;
}

The a ^ b calculates the XOR which is the difference in bit representation of two integers and h & (h – 1) removes the LSB (least significant bit). For example, 11100 & 11011 = 11000. 10001 & 10000 = 10000.

You can test the above JS code to compute the hamming distances between two integers in this online JS editor.

JS The Hamming Distance Implementation in Javascript

NodeJs / Javascript

Hamming Weight / Hamming Distance Algorithms

Here are the posts related to Hamming Distance (XOR, The number of different bits):

–EOF (The Ultimate Computing & Technology Blog) —

546 words
Last Post: Introducing SteemIt Auto Claim Rewards
Next Post: SteemVBS Development - GetVotingPower, Get Post URL from Comment, Suggested Password, Effective SP, VestsToSP and more!

The Permanent URL is: The Hamming Distance Implementation in Javascript (AMP Version)

One Response

Leave a Reply