Skip to content

Commit d8c9c1a

Browse files
author
Sedat Aybars Nazlica
authored
Add Hamming Distance (TheAlgorithms#3164)
1 parent e572354 commit d8c9c1a

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.thealgorithms.strings;
2+
3+
/* In information theory, the Hamming distance between two strings of equal length
4+
is the number of positions at which the corresponding symbols are different.
5+
https://en.wikipedia.org/wiki/Hamming_distance
6+
*/
7+
public class HammingDistance {
8+
9+
/**
10+
* calculate the hamming distance between two strings of equal length
11+
*
12+
* @param s1 the first string
13+
* @param s2 the second string
14+
* @return {@code int} hamming distance
15+
* @throws Exception
16+
*/
17+
public static int calculateHammingDistance(String s1, String s2) throws Exception {
18+
if (s1.length() != s2.length()) {
19+
throw new Exception("String lengths must be equal");
20+
}
21+
22+
int stringLength = s1.length();
23+
int counter = 0;
24+
25+
for (int i = 0; i < stringLength; i++) {
26+
if (s1.charAt(i) != s2.charAt(i)) {
27+
counter++;
28+
}
29+
}
30+
return counter;
31+
}
32+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.thealgorithms.strings;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.assertEquals;
6+
import static org.junit.jupiter.api.Assertions.assertThrows;
7+
8+
public class HammingDistanceTest {
9+
@Test
10+
void testHammingDistance() throws Exception {
11+
assertEquals(HammingDistance.calculateHammingDistance("", ""), 0);
12+
assertEquals(HammingDistance.calculateHammingDistance("java", "java"), 0);
13+
assertEquals(HammingDistance.calculateHammingDistance("karolin", "kathrin"), 3);
14+
assertEquals(HammingDistance.calculateHammingDistance("kathrin", "kerstin"), 4);
15+
assertEquals(HammingDistance.calculateHammingDistance("00000", "11111"), 5);
16+
}
17+
18+
@Test
19+
void testNotEqualStringLengths() {
20+
Exception exception = assertThrows(Exception.class, () -> HammingDistance.calculateHammingDistance("ab", "abc"));
21+
assertEquals("String lengths must be equal", exception.getMessage());
22+
}
23+
}

0 commit comments

Comments
 (0)