
Example: Luhn Algorithm - Generate Mod10 KID Control Digit
This example demonstrates how to add a modulo-10 (Mod10) control digit to a string of numbers using the Luhn algorithm. The Luhn algorithm is widely used for validating credit card numbers and other identification numbers.
For more details, you can refer to Wikipedia's article about the Luhn Algorithm.
Example Function:
function AddMod10(string number)
array int digits;
int l = length(number);
int i;
// Check if the input contains only digits.
if (regex_match("\d+", number)) then
// Build an array of integers.
for (i = 1, l)
digits[] = ascii(substring(number, i - 1, 1)) - 48;
end for
// Back traverse every second digit and double it. If > 9, subtract 9.
for (i = l, 1, -2)
digits[i] = digits[i] * 2;
if (digits[i] > 9) then
digits[i] = digits[i] - 9;
end if
end for
// Calculate the sum of all digits.
int sum;
for (i = 1, l)
sum += digits[i];
end for
// Calculate the control digit.
int digx = mod(sum * 9, 10);
return number + digx;
else
return "ERROR: Expects only digits as parameter: " + number;
end if
end
Result Test:
// For the example from the Wikipedia article mentioned above:
// 7992739871x
Set Variable ($KID; ACF_run("AddMod10"; "7992739871"))
// The return value will be: 79927398713, where the control digit is 3.
References:
Comparison with Standard Custom Functions:
In this example, we've implemented the Luhn algorithm to generate a Mod10 control digit for a given string of numbers. We also perform error checking to ensure that the source string contains only digits. This approach is designed to catch any unexpected characters in the input.
For comparison, there are standard custom functions available on Brian Dunning's website that provide similar functionality:
However, it's worth noting that these functions may not perform the same level of error checking as the example provided here. Using regular expressions to validate the input can help prevent errors and ensure accurate results.
This section provides a detailed example of how to implement the Luhn algorithm to generate a Mod10 control digit for a string of numbers in ACF, including error checking to ensure the input consists of digits only.