HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Hamming distance implementation in JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
hammingimplementationdistancejavascript

Problem

The Hamming distance is a measure of the difference between two strings of equal length. It is calculated by counting the number of positions at which the corresponding characters differ.
@Quick refresher
Implementing it in JavaScript is pretty straightforward, using the XOR operator (^) to find the bit difference between two numbers. We then convert the result to a binary string, using Number.prototype.toString(), and count the number of 1s in it, using String.prototype.match().

Solution

const hammingDistance = (num1, num2) =>
  ((num1 ^ num2).toString(2).match(/1/g) || '').length;

hammingDistance(2, 3); // 1


Implementing it in JavaScript is pretty straightforward, using the XOR operator (^) to find the bit difference between two numbers. We then convert the result to a binary string, using Number.prototype.toString(), and count the number of 1s in it, using String.prototype.match().

Code Snippets

const hammingDistance = (num1, num2) =>
  ((num1 ^ num2).toString(2).match(/1/g) || '').length;

hammingDistance(2, 3); // 1

Context

From 30-seconds-of-code: hamming-distance

Revisions (0)

No revisions yet.