Module:Verhoeff
From CHIPPS
More actions
Documentation for this module may be created at Module:Verhoeff/doc
verhoeff_mult =
{
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{1, 2, 3, 4, 0, 6, 7, 8, 9, 5},
{2, 3, 4, 0, 1, 7, 8, 9, 5, 6},
{3, 4, 0, 1, 2, 8, 9, 5, 6, 7},
{4, 0, 1, 2, 3, 9, 5, 6, 7, 8},
{5, 9, 8, 7, 6, 0, 4, 3, 2, 1},
{6, 5, 9, 8, 7, 1, 0, 4, 3, 2},
{7, 6, 5, 9, 8, 2, 1, 0, 4, 3},
{8, 7, 6, 5, 9, 3, 2, 1, 0, 4},
{9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
}
verhoeff_perm = {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}
verhoeff_inv = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9}
function verhoeff(xs_r)
xs = xs_r:reverse()
c = 0
for i=1,xs:len(),1
do
p = xs:sub(i,i)
for j=1,((i-1)%8),1
do
p = verhoeff_perm[p+1]
end
c = verhoeff_mult[c+1][p+1]
end
return c
end
function verhoeff_verify(str)
return verhoeff(str) == 0
end
function verhoeff_gen(str)
return str..verhoeff_inv[verhoeff(str.."0")+1]
end
function identity(x) return x end
id_to_n = { R=1, L=2, S=3, A=3, E=4 }
function wrm_idproc(str_r, func, pp, gc)
str_stripped = str_r:upper():gsub("^WRM%-?", "")
prefix = str_stripped:match("^[RLSAE]")
res = func(str_stripped:gsub("([RLSAE]?)(%d+)",
function(p, ds, x)
return (gc and "%u%05u" or "%u%06u"):format(id_to_n[p] or 0, ds)
end))
if pp
then
return ("WRM-%s%04u"):format(prefix or "", res:sub(2))
else
return res
end
end
function wrm_gencheck(str_r)
return wrm_idproc(str_r, verhoeff_gen, true, true)
end
function wrm_verifycheck(str_r)
return wrm_idproc(str_r, verhoeff_verify, false, false)
end
local p = {gen=wrm_gencheck, verify=wrm_verifycheck}
return p