Skip to content

Commit e5568cc

Browse files
michael-berger-FRFridaTveit
authored andcommitted
Update hamming reference (exercism#1660)
* Update hamming reference Java track/Hamming exercise/reference implementation: offer a more modern solution (Java 8), including a more concise management of exceptions * [exercism/java] Update hamming reference Includes @FridaTveit feedback
1 parent 2648325 commit e5568cc

1 file changed

Lines changed: 16 additions & 26 deletions

File tree

Lines changed: 16 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,26 @@
1+
import java.util.function.IntPredicate;
2+
import java.util.stream.IntStream;
3+
14
class Hamming {
25
private final int hammingDistance;
36

47
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);
2717
}
2818

29-
return distance;
19+
IntPredicate areNotEqual = index -> leftStrand.charAt(index) != rightStrand.charAt(index);
20+
hammingDistance = (int) IntStream.range(0, leftStrand.length()).filter(areNotEqual).count();
3021
}
3122

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;
3425
}
35-
3626
}

0 commit comments

Comments
 (0)