Last active
December 25, 2016 20:42
-
-
Save l-ray/a6ecbf2f3b496634ee83 to your computer and use it in GitHub Desktop.
Modulo10 / Mod10 / Luhn algorithm in Gosu
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
uses java.lang.Integer | |
uses java.util.Arrays | |
uses java.lang.Character | |
uses java.util.ArrayList | |
class ModuloTenProcessor { | |
/** | |
* Validate a number string using Luhn algorithm | |
*/ | |
@Param("numberString", "Number to be checked") | |
@Returns("True, if number is valid") | |
static function isValid(numberString : String ):boolean { | |
return checkSum(numberString,true) == 0; | |
} | |
/** | |
* Generate check digit for a number string. | |
* | |
*/ | |
@Param("numberString","Number as String that needs to be checksummed, no checksum as last digit already existing") | |
@Returns("Checksum-digit") | |
public static function checkSum(numberString:String):int { | |
return checkSum(numberString,false) | |
} | |
/** | |
* Generate check digit for a number string. | |
* | |
*/ | |
@Param("numberString","Number as String that needs to be checksummed") | |
@Param("checkDigitAttached","does the number already hold a checksum-digit as the last position") | |
@Returns("Checksum-digit") | |
public static function checkSum(numberString:String, checkDigitAttached:boolean):int { | |
var sum:int = 0 | |
var checkDigit:int = 0 | |
var numberArray:List<Integer> = convertToNumberArray(numberString) | |
print(numberArray) | |
numberArray = numberArray.reverse() | |
print(numberArray) | |
numberArray.eachWithIndex( \ number, index -> { | |
var newNumber = (number * (index % 2 == (checkDigitAttached?1:0) ? 2 : 1)) | |
var newTotal = crossTotal(newNumber) | |
print("currentSum:"+newTotal+" number:"+number + " modified number:"+newNumber +" crossTotal:"+newTotal+ " isOdd:"+ (index % 2 == 1)) | |
sum += newTotal | |
} | |
) | |
return ((sum % 10) > 0) ? (10 - (sum % 10)) : 0 | |
} | |
// returns given String as array of digits | |
private static function convertToNumberArray(numberString:String) : List<Integer> { | |
var numberArray:List<Integer> = new ArrayList<Integer>(numberString.length) | |
for (var myChar in numberString.toCharArray() index i) { | |
if (Character.isDigit(myChar)) { | |
numberArray.add(Character.getNumericValue(myChar)) | |
} | |
} | |
return numberArray | |
} | |
/** | |
* Returns the cross-total of a given number. That means, it returns the sum of the digits of that number. | |
*/ | |
@Param ( "k", "Number" ) | |
@Returns ( "Cross-total of the given number" ) | |
public static function crossTotal(k:int):int { | |
return k < 10 ? k : crossTotal(k / 10) + (k % 10); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment