Bläddra i källkod

luhn: fix example solution

Previously this code was applying the required operations to every
second digit starting from the LEFT. The correct solution applies the
required operations to every second digit starting from the RIGHT. The
fact that this was not caught by the tests is a problem! The canonical
tests have been updated since this exercise was last overhauled, so next
steps should be to update to match the expanded canonical test suite,
then test against a broken implementation to see if it is now caught.
Even if it is, it may be worth including an explicit left vs right test
in the canonical suite if one does not already exist.
Stuart Kent 9 år sedan
förälder
incheckning
0e59f34128
1 ändrade filer med 8 tillägg och 1 borttagningar
  1. 8
    1
      exercises/luhn/src/example/java/LuhnValidator.java

+ 8
- 1
exercises/luhn/src/example/java/LuhnValidator.java Visa fil

@@ -9,9 +9,12 @@ final class LuhnValidator {
9 9
     boolean isValid(final String candidate) {
10 10
         final String sanitizedCandidate = SPACE_PATTERN.matcher(candidate).replaceAll("");
11 11
 
12
+        // We need to alter every second digit counting from the right. Reversing makes this easy!
13
+        final String reversedSanitizedCandidate = reverse(sanitizedCandidate);
14
+
12 15
         final List<Integer> computedDigits = new ArrayList<>();
13 16
 
14
-        for (int charIndex = 0; charIndex < sanitizedCandidate.length(); charIndex++) {
17
+        for (int charIndex = 0; charIndex < reversedSanitizedCandidate.length(); charIndex++) {
15 18
             int inputDigit = Character.digit(sanitizedCandidate.charAt(charIndex), 10);
16 19
 
17 20
             /*
@@ -40,4 +43,8 @@ final class LuhnValidator {
40 43
         return digitSum > 0 && digitSum % 10 == 0;
41 44
     }
42 45
 
46
+    private String reverse(final String string) {
47
+        return new StringBuilder(string).reverse().toString();
48
+    }
49
+
43 50
 }