Created
June 1, 2016 16:33
-
-
Save dreidpath/543ffc1e4bc322f39f1286e495350ea4 to your computer and use it in GitHub Desktop.
Luhn Test: Numbers like creidt cards have a check digit at the end. Given a string of numbers, the Luhn Test wil determine if the last number is the correct check digit
This file contains 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
luhnTest <- function(cc){ | |
# cc: the number to test | |
# Reverse the digits, convert to numeric vector; see: https://en.wikipedia.org/wiki/Luhn_algorithm | |
# The code originally appeared in http://megasnippets.com/source-codes/r/luhn_test_credit_card_numbers | |
cc2 <- as.numeric(unlist(strsplit(as.character(cc), "")))[nchar(cc):1] | |
s1 <- 0 | |
s2 <- 0 | |
for (index in 1:length(cc2)){ | |
if (index %% 2 == 1){ | |
s1 <- sum(s1, cc2[index]) | |
} else if (cc2[index] >= 5){ | |
s2 <- sum(s2, (cc2[index]*2 - 9)) | |
} else { | |
s2 <- sum(s2, (cc2[index]*2)) | |
} | |
} | |
return ((s1 + s2) %% 10 == 0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment