Damm’s Algorithm
November 18, 2014
This is simple; here are the table and two functions:
(define damm '#(
#(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 9)
#(2 5 8 1 4 3 6 7 9 0)))
(define (check num)
(let loop ((d 0) (ds (digits num)))
(if (null? ds) (+ (* num 10) d)
(loop (vector-ref (vector-ref damm d) (car ds)) (cdr ds)))))
(define (valid? num)
(let loop ((d 0) (ds (digits num)))
(if (null? ds) (zero? d)
(loop (vector-ref (vector-ref damm d) (car ds)) (cdr ds)))))
And here are some examples:
> (check 572)
5724
> (valid? 5724)
#t
We used digits
from the Standard Prelude. You can run the program at http://programmingpraxis.codepad.org/mIPEQIZX.
It is a mystery to my why the Luhn algorithm is so often used, whereas the Damm algorithm is so seldom used. The Damm algorithm finds all single-digit errors and all adjacent-digit transpositions; Luhn’s algorithm finds most, but not all. And Damm’s algorithm is arguably simpler, using table lookup instead of arithmetic. Perhaps Luhn is preferred because it was available first, and because it doesn’t require space to store the lookup table (though at only 100 half-bytes, the table size is probably about the same memory size as the program code).
Haskell: http://codepad.org/plvEcNXF
Having leading zeroes not affect the check digit makes things a bit simpler.
Didn’t read the directions carefully.
check
should return10 * n + i
, and the test at the end can be simplified toverify(check(n))
. Sorry!On my laptop, using a dict of dicts for the table and processing the number as a string, is about twice as fast as using a list of lists and processing the number as digits (i.e., ints).
I’ve been getting into Clojure lately:
Just to let you guys know, the lookup table you’re using is incorrect. The 8th row, 9th column should be a 5. https://en.wikipedia.org/wiki/Damm_algorithm