Last active
December 24, 2019 13:15
-
-
Save trdev7/ecdce7b602e2bb749a2c16639ce2a7d8 to your computer and use it in GitHub Desktop.
This Ruby file includes Ruby functions that Luhn algorithm is implemented. Function ,"checkLuhn1 check if current barcode(included check digit) validates. Function, "checkLuhn2" returns value that current barcode join with its checkdigit as suffix. /********************************************/ [note] Here, I have used Bitwise Operator instead o…
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
def sumLuhn (barcode, nParity) | |
checksum = 0 | |
for i in 0..barcode.length - 1 | |
nDigit = barcode[i].to_i | |
if nParity == ( i & 1 ) # i % 2 | |
nDigit = ( nDigit << 1 ) # nDigit * 2 | |
end | |
checksum = checksum + nDigit / 10 + nDigit % 10 | |
end | |
return checksum % 10 | |
end | |
#return turn if current barcode( including checkdigit ) validates, false if not. | |
def checkLuhn1(barcode) | |
nParity = ( barcode.length & 1 ) # barcode.length % 2 | |
return sumLuhn(barcode, nParity) == 0 | |
end | |
#return string if current barcode joined checkdigit as suffix. | |
def checkLuhn2(barcode) | |
nParity = ( 1 ^ ( barcode.length & 1 ) ) # 1 - ( barcode.length % 2 ) | |
checksum = sumLuhn(barcode, nParity) | |
return barcode + "#{ ( 10 - checksum % 10 ) % 10 }" | |
end | |
puts checkLuhn1( "79927398713" ) # return ture if valid barcode, return false if invalid barcode | |
puts checkLuhn2( "7992739871" ) # return checkcode |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment