Hamming Distance
Definition​
- Definition
- Explanation
- Guidance
- Tips
The Hamming Distance Algorithm calculates the number of positions at which corresponding symbols differ between two strings of equal length
The algorithm iterates over each symbol in the strings and compares them. It increments a counter whenever it finds a difference. The final count represents the Hamming distance
- Take two strings as input, ensuring they are of equal length
- Initialize a variable
distance
to0
to keep track of differences - Iterate over each character in the strings simultaneously
- Compare characters at the same position in both strings
- If characters differ, increment
distance
by1
- Continue until you've checked all positions
- Return the value of
distance
- ensure both strings are of equal length before applying the algorithm
- optimize by exiting the loop early if the lengths of the strings are exceeded
Practice​
- Practice
- Solution
hammingDistance(string1, string2):
if length(string1) ≠length(string2):
throw "Error: Strings must be of equal length"
distance = 0
for i = 0 to length(string1) - 1:
if string1[i] ≠string2[i]:
distance += 1
return distance
package main
func hammingDistance(str1, str2 string) int {
if len(str1) != len(str2) {
return -1
}
distance := 0
for i := 0; i < len(str1); i++ {
if str1[i] != str2[i] {
distance++
}
}
return distance
}
public class HammingDistance {
public static int hammingDistance(String str1, String str2) {
if (str1.length() != str2.length()) {
return -1;
}
int distance = 0;
for (int i = 0; i < str1.length(); i++) {
if (str1.charAt(i) != str2.charAt(i)) {
distance++;
}
}
return distance;
}
}
function hammingDistance(str1, str2) {
if (str1.length !== str2.length) {
return -1;
}
let distance = 0;
for (let i = 0; i < str1.length; i++) {
if (str1[i] !== str2[i]) {
distance++;
}
}
return distance;
}
fun hammingDistance(str1: String, str2: String): Int {
require(str1.length == str2.length) { "Strings must be of equal length" }
var distance = 0
for (i in str1.indices) {
if (str1[i] != str2[i]) {
distance++
}
}
return distance
}
def hamming_distance(str1, str2):
if len(str1) != len(str2):
return -1
distance = 0
for char1, char2 in zip(str1, str2):
if char1 != char2:
distance += 1
return distance
fn hamming_distance(str1: &str, str2: &str) -> Result<usize, &'static str> {
if str1.len() != str2.len() {
return Err("Strings must be of equal length");
}
let mut distance = 0;
for (c1, c2) in str1.chars().zip(str2.chars()) {
if c1 != c2 {
distance += 1;
}
}
Ok(distance)
}
function hammingDistance(str1: string, str2: string): number {
if (str1.length !== str2.length) {
return -1;
}
let distance = 0;
for (let i = 0; i < str1.length; i++) {
if (str1[i] !== str2[i]) {
distance++;
}
}
return distance;
}