|
| 1 | +import java.util.function.IntPredicate; |
| 2 | +import java.util.stream.IntStream; |
| 3 | + |
1 | 4 | class Hamming { |
2 | 5 | private final int hammingDistance; |
3 | 6 |
|
4 | 7 | Hamming(String leftStrand, String rightStrand) { |
5 | | - hammingDistance = computeHammingDistance(leftStrand, rightStrand); |
6 | | - } |
7 | | - |
8 | | - int getHammingDistance() { |
9 | | - return hammingDistance; |
10 | | - } |
11 | | - |
12 | | - private int computeHammingDistance(String leftStrand, String rightStrand) { |
13 | | - if (leftStrand.length() == 0 && rightStrand.length() == 0) { |
14 | | - return 0; |
15 | | - } else if (leftStrand.length() == 0) { |
16 | | - throw new IllegalArgumentException("left strand must not be empty."); |
17 | | - } else if (rightStrand.length() == 0) { |
18 | | - throw new IllegalArgumentException("right strand must not be empty."); |
19 | | - } else if (leftStrand.length() != rightStrand.length()) { |
20 | | - throw new IllegalArgumentException("leftStrand and rightStrand must be of equal length."); |
21 | | - } |
22 | | - |
23 | | - int length = leftStrand.length(); |
24 | | - int distance = 0; |
25 | | - for (int i = 0; i < length; i++) { |
26 | | - distance += hammingContributionAt(i, leftStrand, rightStrand); |
| 8 | + String exceptionMessage = "leftStrand and rightStrand must be of equal length."; |
| 9 | + if (leftStrand.length() != rightStrand.length()) { |
| 10 | + if (leftStrand.isEmpty()) { |
| 11 | + exceptionMessage = "left strand must not be empty."; |
| 12 | + } |
| 13 | + if (rightStrand.isEmpty()) { |
| 14 | + exceptionMessage = "right strand must not be empty."; |
| 15 | + } |
| 16 | + throw new IllegalArgumentException(exceptionMessage); |
27 | 17 | } |
28 | 18 |
|
29 | | - return distance; |
| 19 | + IntPredicate areNotEqual = index -> leftStrand.charAt(index) != rightStrand.charAt(index); |
| 20 | + hammingDistance = (int) IntStream.range(0, leftStrand.length()).filter(areNotEqual).count(); |
30 | 21 | } |
31 | 22 |
|
32 | | - private int hammingContributionAt(int index, String leftStrand, String rightStrand) { |
33 | | - return leftStrand.charAt(index) != rightStrand.charAt(index) ? 1 : 0; |
| 23 | + int getHammingDistance() { |
| 24 | + return hammingDistance; |
34 | 25 | } |
35 | | - |
36 | 26 | } |
0 commit comments