aboutsummaryrefslogtreecommitdiff
path: root/damm/damm.go
diff options
context:
space:
mode:
authorAlexander Kiryukhin <a.kiryukhin@mail.ru>2019-08-30 01:43:12 +0300
committerAlexander Kiryukhin <a.kiryukhin@mail.ru>2019-08-30 01:43:12 +0300
commit878cb24695b7d39fa9de65a1e164abc84dc67ead (patch)
tree73946dd08310c2a3b7535297906a4ff5535db756 /damm/damm.go
parentb0fba45d68c9ec6c2274ebd61b28ca22bb5deff6 (diff)
Added Damm algorithm
Diffstat (limited to 'damm/damm.go')
-rw-r--r--damm/damm.go49
1 files changed, 49 insertions, 0 deletions
diff --git a/damm/damm.go b/damm/damm.go
new file mode 100644
index 0000000..388eb00
--- /dev/null
+++ b/damm/damm.go
@@ -0,0 +1,49 @@
+package damm
+
+import (
+ "strconv"
+
+ "github.com/neonxp/checksum"
+)
+
+var d = [10][10]int{
+ {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},
+}
+
+// Check number is correct by damm algorithm
+func Check(number string) error {
+ c := 0
+ for _, ch := range number {
+ num, err := strconv.Atoi(string(ch))
+ if err != nil {
+ return checksum.ErrInvalidNumber
+ }
+ c = d[c][num]
+ }
+ if c != 0 {
+ return checksum.ErrInvalidChecksum
+ }
+ return nil
+}
+
+// Generate checksum (must be added to number at right)
+func Generate(number string) (string, error) {
+ c := 0
+ for _, ch := range number {
+ num, err := strconv.Atoi(string(ch))
+ if err != nil {
+ return "", checksum.ErrInvalidNumber
+ }
+ c = d[c][num]
+ }
+ return strconv.Itoa(c), nil
+}