I recently came across some programming challenges online that I decided to try out. They are heavily math based and took me quite a bit of research. This particular challenge was to both calculate a check digit on a credit card and validate a credit card number. The algorithm I found that does this best is called Luhn Algorithm.
Luhn Algorithm is described as the following (via Wikipedia):
Based on this description, I came up with the following code:
public static class LuhnAlgorithm { private static readonly int[] DoubleDigitCalculation = { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 }; public static int GetLuhnsCheckDigit(this string account) { int checkValue = LuhnsCalculation(account.Select(c => c - '0').ToArray(), false); return checkValue == 0 ? 0 : 10 - checkValue; } public static bool LuhnsPass(this string account) { return LuhnsCalculation(account.Select(c => c - '0').ToArray(), true) == 0; } private static int LuhnsCalculation(int[] digits, bool includesCheckDigit) { int index = 0; int modIndex = includesCheckDigit ? digits.Length % 2 : digits.Length % 2 == 1 ? 0 : 1; return digits.Sum(d => index++ % 2 == modIndex ? DoubleDigitCalculation[d] : d) % 10; } }
This bit of code passed all the tests and is very fast. Although it doesn't have a ton of use, it was fun to come up with.