Repository: TheAlgorithms/Java
Pull request #4218 (2023-06-21 13:55:50)

refactor: simplify `HammingDistance`
I have found few problems with the implementation of [`HammingDistance`](https://github.com/TheAlgorithms/Java/blob/7a3273ae1db2a652b80a4b655e642f06331937cb/src/main/java/com/thealgorithms/others/cn/HammingDistance.java#L6), namely:
- unnecessary conversion from `String` to `byte[]`,
- I think that this implementation was aiming to handle only `String`s containing only `0`s and `1`s, but this is not checked anywhere.

This PR:
- makes a _proper utility_ class out of `HammingDistance` in 610def7764dee995373d0e7a6ded5e0a1af644ed,
- simplifies logic of some existing tests and adds tests against empty input and input of length `1` in 58f7da387e1916ca169b25a5c3547e5df56f1ffc,
- simplifies logic in class `HammingDistance`, updates naming and changes the behaviour for _non-binary strings_ in 00d54bdbd048ece0fd15f597a65e05d4b4ec5d60,
- removes [redundant logging](https://github.com/TheAlgorithms/Java/pull/3270#discussion_r977520848) in 32b12432659485a2a4c802f4377b6a77f8534c26.

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.



Patch:
diff --git a/src/main/java/com/thealgorithms/others/cn/HammingDistance.java b/src/main/java/com/thealgorithms/others/cn/HammingDistance.java
index 8a73e5ac..38bfc0a5 100644
--- a/src/main/java/com/thealgorithms/others/cn/HammingDistance.java
+++ b/src/main/java/com/thealgorithms/others/cn/HammingDistance.java
@@ -3,32 +3,33 @@ package com.thealgorithms.others.cn;
 import java.util.ArrayList;
 import java.util.List;
 
-public class HammingDistance {
+final public class HammingDistance {
+    private HammingDistance() {
+    }
 
-    public int getHammingDistanceBetweenBits(String senderBits, String receiverBits) {
-        if (senderBits.length() != receiverBits.length()) {
-            throw new IllegalArgumentException("Sender and Receiver bits should be same");
+    private static void checkChar(char inChar) {
+        if (inChar != '0' && inChar != '1') {
+            throw new IllegalArgumentException("Input must be a binary string.");
         }
+    }
 
-        List<byte[]> byteArray = new ArrayList<>();
-
-        byteArray.add(senderBits.getBytes());
-        byteArray.add(receiverBits.getBytes());
+    public static int compute(char charA, char charB) {
+        checkChar(charA);
+        checkChar(charB);
+        return charA == charB ? 0 : 1;
+    }
 
-        byte[] senderData = byteArray.get(0);
-        byte[] receiverData = byteArray.get(1);
+    public static int compute(String bitsStrA, String bitsStrB) {
+        if (bitsStrA.length() != bitsStrB.length()) {
+            throw new IllegalArgumentException("Input strings must have the same length.");
+        }
 
         int totalErrorBitCount = 0;
 
-        for (int i = 0; i < senderData.length; i++) {
-            totalErrorBitCount += senderData[i] ^ receiverData[i];
+        for (int i = 0; i < bitsStrA.length(); i++) {
+            totalErrorBitCount += compute(bitsStrA.charAt(i), bitsStrB.charAt(i));
         }
 
-        if (totalErrorBitCount == 0) {
-            System.out.println("No Error bit in data segments");
-        } else {
-            System.out.println("Total Error bit count " + totalErrorBitCount);
-        }
         return totalErrorBitCount;
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java b/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java
index cd4bc0ff..4713af07 100644
--- a/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java
+++ b/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java
@@ -6,18 +6,9 @@ import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
 public class HammingDistanceTest {
-
-    HammingDistance hd;
-
-    @BeforeEach
-    void initialize() {
-        hd = new HammingDistance();
-    }
-
     @Test
     public void checkForDifferentBits() {
-        String senderBits = "000", receiverBits = "011";
-        int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits);
+        int answer = HammingDistance.compute("000", "011");
         Assertions.assertThat(answer).isEqualTo(2);
     }
 
@@ -32,38 +23,62 @@ public class HammingDistanceTest {
  */
     @Test
     public void checkForDifferentBitsLength() {
-        String senderBits = "10101", receiverBits = "11110";
-        int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits);
+        int answer = HammingDistance.compute("10101", "11110");
         Assertions.assertThat(answer).isEqualTo(3);
     }
 
     @Test
     public void checkForSameBits() {
-        String senderBits = "111", receiverBits = "111";
-        int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits);
+        String someBits = "111";
+        int answer = HammingDistance.compute(someBits, someBits);
         Assertions.assertThat(answer).isEqualTo(0);
     }
 
     @Test
     public void checkForLongDataBits() {
-        String senderBits = "10010101101010000100110100", receiverBits = "00110100001011001100110101";
-        int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits);
+        int answer = HammingDistance.compute("10010101101010000100110100", "00110100001011001100110101");
         Assertions.assertThat(answer).isEqualTo(7);
     }
 
     @Test
     public void mismatchDataBits() {
-        String senderBits = "100010", receiverBits = "00011";
+        Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> { int answer = HammingDistance.compute("100010", "00011"); });
+
+        Assertions.assertThat(ex.getMessage()).contains("must have the same length");
+    }
 
-        Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> { int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits); });
+    @Test
+    public void mismatchDataBits2() {
+        Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> { int answer = HammingDistance.compute("1", "11"); });
 
-        Assertions.assertThat(ex.getMessage()).contains("bits should be same");
+        Assertions.assertThat(ex.getMessage()).contains("must have the same length");
     }
 
     @Test
     public void checkForLongDataBitsSame() {
-        String senderBits = "10010101101010000100110100", receiverBits = "10010101101010000100110100";
-        int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits);
+        String someBits = "10010101101010000100110100";
+        int answer = HammingDistance.compute(someBits, someBits);
         Assertions.assertThat(answer).isEqualTo(0);
     }
+
+    @Test
+    public void checkForEmptyInput() {
+        String someBits = "";
+        int answer = HammingDistance.compute(someBits, someBits);
+        Assertions.assertThat(answer).isEqualTo(0);
+    }
+
+    @Test
+    public void checkForInputOfLength1() {
+        String someBits = "0";
+        int answer = HammingDistance.compute(someBits, someBits);
+        Assertions.assertThat(answer).isEqualTo(0);
+    }
+
+    @Test
+    public void computeThrowsExceptionWhenInputsAreNotBitStrs() {
+        Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> { int answer = HammingDistance.compute("1A", "11"); });
+
+        Assertions.assertThat(ex.getMessage()).contains("must be a binary string");
+    }
 }