Skip to content

Commit

Permalink
Update Luhn tests and sample implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
stkent committed Jan 18, 2017
1 parent 6c1ae65 commit 74010f4
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 185 deletions.
90 changes: 0 additions & 90 deletions exercises/luhn/src/example/java/Luhn.java

This file was deleted.

40 changes: 40 additions & 0 deletions exercises/luhn/src/example/java/LuhnValidator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

final class LuhnValidator {

private static final Pattern SPACE_PATTERN = Pattern.compile("\\s+");

boolean isValid(final String candidate) {
final String sanitizedCandidate = SPACE_PATTERN.matcher(candidate).replaceAll("");

final List<Integer> computedDigits = new ArrayList<>();

for (int charIndex = 0; charIndex < sanitizedCandidate.length(); charIndex++) {
int inputDigit = Character.getNumericValue(sanitizedCandidate.charAt(charIndex));

// Character.getNumericValue returns a negative int if the supplied character does not represent a digit.
if (inputDigit < 0) {
return false;
}

if (charIndex % 2 == 1) {
/*
* Since our doubled input digit must lie in [2, 18], the operation
*
* "subtract 9 from the doubled input digit if it exceeds 9 in value"
*
* is equivalent to applying the modulo operation below universally.
*/
inputDigit = (2 * inputDigit) % 9;
}

computedDigits.add(inputDigit);
}

final int digitSum = computedDigits.stream().mapToInt(Integer::intValue).sum();
return digitSum > 0 && digitSum % 10 == 0;
}

}
95 changes: 0 additions & 95 deletions exercises/luhn/src/test/java/LuhnTest.java

This file was deleted.

39 changes: 39 additions & 0 deletions exercises/luhn/src/test/java/LuhnValidatorTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Collection;

import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)
public class LuhnValidatorTest {

@Parameterized.Parameters(name="When checking if {0} is valid, the answer should be {1}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{
{"1", false},
{"0", false},
{"046 454 286", true},
{"046 454 287", false},
{"8273 1232 7352 0569", false},
{"046a 454 286", false},
});
}

private final String candidate;

private final boolean expectedToBeValid;

public LuhnValidatorTest(final String candidate, final boolean expectedToBeValid) {
this.candidate = candidate;
this.expectedToBeValid = expectedToBeValid;
}

@Test
public void test() {
assertEquals(expectedToBeValid, new LuhnValidator().isValid(candidate));
}

}

0 comments on commit 74010f4

Please sign in to comment.