mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-09 12:11:28 +08:00
refactor: simplify HammingDistance
(#4218)
* refactor: make HammingDistance an utility class * tests: add some tests, simplify logic of some * refator: simplify logic in HammingDistance * style: remove logging messages
This commit is contained in:
@ -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<>();
|
||||
public static int compute(char charA, char charB) {
|
||||
checkChar(charA);
|
||||
checkChar(charB);
|
||||
return charA == charB ? 0 : 1;
|
||||
}
|
||||
|
||||
byteArray.add(senderBits.getBytes());
|
||||
byteArray.add(receiverBits.getBytes());
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user