Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

This module implements the Verhoeff check digit algorithm in Lua.

Usage

verhoeff_gen(str)

Generates a Verhoeff algorithm check digit for str and returns the digit string with check digit appended.

verhoeff_verify(str)

Verifies the check digit at the end of str according to the Verhoeff algorithm, returning true iff successful.


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 }

return {verhoeff_verify=verhoeff_verify, verhoeff_gen=verhoeff_gen}