Sunday, 20 December 2015

Luhn validator

Got a bit confused whilst testing something at work as one of the luhn validation tools at work decided to change it's mind around what the check digit should be, I wrote my own:

Luhn algorithm

package com.company;

public class luhnValidator {
    public boolean isValidLuhn(String inputNumber) {
        int[] numbers = stringToIntArray(inputNumber);
        specialDoubler(numbers);
        int total = sumIntArray(numbers);

        return (total * 9) % 10 == numbers[numbers.length-1] ;
    }

    public int checkDigitCalc(String numberWithNoCheckDigit) {
        int[] numbers = stringToIntArray(numberWithNoCheckDigit);
        specialDoubler(numbers);
        int total = sumIntArray(numbers);

        return (total * 9) % 10;
    }

    private int[] stringToIntArray(String convertToNumbers) {
        char[] brokenToChars = convertToNumbers.toCharArray();
        int[] numbers = new int[brokenToChars.length];
        for (int i = 0; i < brokenToChars.length; i++) {
            numbers[i] = Character.getNumericValue(brokenToChars[i]) ;
        }

        return numbers;
    }

    /**
     * Double every second number if greater than 10 add the products together
     */
    private void specialDoubler(int[] numbers) {
        int x2;
        for (int i = numbers.length-2; i >= 0; i -= 2) {
            x2 = numbers[i] * 2;
            if (x2 < 10) {
                numbers[i] = x2;
            } else {
                numbers[i] = (x2 - 10) + 1;
            }
        }
    }

    private int sumIntArray(int[] numbers) {
        int total = 0;
        for (int i = 0; i < numbers.length-1; i++ ) {
            total += numbers[i];
        }
        return total;
    }
}





Could still be optimised but it was fun to play with the intellij tests for jUnit, as they did help pick out a simple error where I missed out the '>' in >=.

No comments:

Post a Comment