Skip to content

Instantly share code, notes, and snippets.

@taylortrimble
Created April 1, 2018 22:22
Show Gist options
  • Save taylortrimble/24647c2c5427163dafa5fa9e732889dd to your computer and use it in GitHub Desktop.
Save taylortrimble/24647c2c5427163dafa5fa9e732889dd to your computer and use it in GitHub Desktop.
Damm check digit package for golang
package damm
import "strconv"
// DefaultDamm10 has as its Matrix a 10x10 totally anti-symmetric quasigroup
// retrieved from Damm's doctoral dissertation.
//
// https://en.wikipedia.org/wiki/Damm_algorithm
var DefaultDamm10 = Damm{Matrix: [][]int{
[]int{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
[]int{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
[]int{4, 2, 0, 6, 8, 7, 1, 3, 5, 9},
[]int{1, 7, 5, 0, 9, 8, 3, 4, 2, 6},
[]int{6, 1, 2, 3, 0, 4, 5, 9, 7, 8},
[]int{3, 6, 7, 4, 2, 0, 9, 5, 8, 1},
[]int{5, 8, 6, 9, 7, 2, 0, 1, 3, 4},
[]int{8, 9, 4, 5, 3, 6, 2, 0, 1, 7},
[]int{9, 4, 3, 8, 6, 1, 7, 2, 0, 5},
[]int{2, 5, 8, 1, 4, 3, 6, 7, 9, 0},
}}
// Damm generates and validates digit strings with a final check digit generated by the Damm algorithm.
type Damm struct {
Matrix [][]int
}
// Create returns the digits string with a Damm check digit appended.
func (damm *Damm) Create(digits string) string {
return digits + strconv.Itoa(damm.checkDigit(digits))
}
// Check validates the last digit in the digits string is a Damm check digit for the rest of the digits.
func (damm *Damm) Check(digits string) bool {
return damm.checkDigit(digits) == 0
}
// checkDigit returns the integer Damm check digit for the digits string.
func (damm *Damm) checkDigit(digits string) int {
interim := 0
for _, r := range digits {
digit, err := strconv.Atoi(string(r))
if err != nil {
panic(err)
}
interim = damm.Matrix[interim][digit]
}
return interim
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment