Skip to content

Instantly share code, notes, and snippets.

@mboeh
Created November 14, 2018 04:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mboeh/5129d5b3f996ffab06d03dc754e6ccd9 to your computer and use it in GitHub Desktop.
Save mboeh/5129d5b3f996ffab06d03dc754e6ccd9 to your computer and use it in GitHub Desktop.
toy implementation of damm algorithm
# https://en.wikipedia.org/wiki/Damm_algorithm
module Damm
extend self
OP_TABLE = [
[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
[3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
[5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
[8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
[9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
[2, 5, 8, 1, 4, 3, 6, 7, 9, 0],
]
def check_digit(num)
num.to_s.chars.map(&:to_i).inject(0) {|c,i|
OP_TABLE[c][i]
}
end
def verify(num)
check_digit(num) == 0
end
def encode(num)
num * 10 + check_digit(num)
end
def decode(num)
if verify(num)
num / 10
end
end
end
p Damm.check_digit(572)
p Damm.verify(5724)
p Damm.encode(572)
p(1000.times.to_a.all? {
n = rand(100000000)
Damm.decode(Damm.encode(n)) == n
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment