local fmt = require "fmt" local d = { {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} } local inv = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9} local p = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8} } local function verhoeff(s, validate, table) if table then print($"{validate ? "Validation" : "Check digit"} calculations for '{s}':\n") print(" i nᵢ p[i,nᵢ] c") print("------------------") end if !validate then s ..= "0" end local c = 0 local le = #s - 1 for i = le, 0, -1 do local ni = s[i + 1]:byte() - 48 local pi = p[(le - i) % 8 + 1][ni + 1] c = d[c + 1][pi + 1] if table then fmt.print("%2d %d %d %d", le - i, ni, pi, c) end end if table and !validate then print($"\ninv[{c + 1}] = {inv[c + 1]}") end return !validate ? inv[c + 1] : c == 0 end local sts = {{"236", true}, {"12345", true}, {"123456789012", false}} for sts as st do local c = verhoeff(st[1], false, st[2]) print($"\nThe check digit for '{st[1]}' is '{c}'\n") for {st[1] .. tostring(c), st[1] .. "9"} as stc do local v = verhoeff(stc, true, st[2]) print($"\nThe validation for '{stc}' is {v ? "correct" : "incorrect"}.\n") end end