Verhoeff algorithm: Difference between revisions
Content added Content deleted
(julia example) |
|||
Line 132: | Line 132: | ||
""" |
""" |
||
Calculate the Verhoeff checksum over `n`. |
Calculate the Verhoeff checksum over `n`. |
||
Terse mode or with single argument: return true if valid (last digit is a correct check digit). |
|||
If checksum mode, return the expected correct checksum digit. |
If checksum mode, return the expected correct checksum digit. |
||
If validation mode, return true if last digit checks correctly. |
If validation mode, return true if last digit checks correctly. |
||
""" |
""" |
||
function verhoeffchecksum(n::Integer, validate=true, verbose=false) |
function verhoeffchecksum(n::Integer, validate=true, terse=true, verbose=false) |
||
verbose && println("\n", validate ? "Validation" : "Check digit", |
verbose && println("\n", validate ? "Validation" : "Check digit", |
||
" calculations for '$n':\n\n", " i nᵢ p[i,nᵢ] c\n------------------") |
" calculations for '$n':\n\n", " i nᵢ p[i,nᵢ] c\n------------------") |
||
Line 147: | Line 148: | ||
end |
end |
||
verbose && !validate && println("\ninv($c) = $(inv[c + 1])") |
verbose && !validate && println("\ninv($c) = $(inv[c + 1])") |
||
⚫ | |||
"correct" : "incorrect")." : "\nThe check digit for '$n' is $(inv[c + 1]).") |
|||
return validate ? c == 0 : inv[c + 1] |
return validate ? c == 0 : inv[c + 1] |
||
end |
end |
||
for args in [(236, false, false, true), (2363, true, false, true), (2369, true, false, true), |
|||
println("\nThe check digit for '236' is $(verhoeffchecksum(236, false, true)).") |
|||
(12345, false, false, true), (123451, true, false, true), (123459, true, false, true), |
|||
println("\nThe validation for '2363' is ", verhoeffchecksum(2363, true, true) ? |
|||
(123456789012, false, false), (1234567890120, true, false), (1234567890129, true, false)] |
|||
"correct" : "incorrect", ".") |
|||
verhoeffchecksum(args...) |
|||
end |
|||
"correct" : "incorrect", ".") |
|||
println("\nThe check digit for '12345' is $(verhoeffchecksum(12345, false, true)).") |
|||
println("\nThe validation for '123451' is ", verhoeffchecksum(123451, true, true) ? |
|||
"correct" : "incorrect", ".") |
|||
println("\nThe validation for '123459' is ", verhoeffchecksum(123459, true, true) ? |
|||
"correct" : "incorrect", ".") |
|||
println("\nThe check digit for '123456789012' is $(verhoeffchecksum(123456789012, false)).") |
|||
⚫ | |||
verhoeffchecksum(1234567890120, true) ? "correct." : "incorrect.") |
|||
println("\nThe validation for '1234567890129' is ", |
|||
verhoeffchecksum(1234567890129, true) ? "correct." : "incorrect.") |
|||
</lang>{{out}}Same as Wren example. |
</lang>{{out}}Same as Wren example. |
||
=={{header|Nim}}== |
=={{header|Nim}}== |