Thursday, February 29, 2024
HomeSoftware EngineeringHow you can Validate ISBN-10 numbers in Golang

How you can Validate ISBN-10 numbers in Golang


The problem

ISBN-10 identifiers are ten digits lengthy. The primary 9 characters are digits 0-9. The final digit may be 0-9 or X, to point a price of 10.

An ISBN-10 quantity is legitimate if the sum of the digits multiplied by their place modulo 11 equals zero.

For instance:

ISBN     : 1 1 1 2 2 2 3 3 3  9
place : 1 2 3 4 5 6 7 8 9 10

It is a legitimate ISBN, as a result of:

(1*1 + 1*2 + 1*3 + 2*4 + 2*5 + 2*6 + 3*7 + 3*8 + 3*9 + 9*10) % 11 = 0

Examples

1112223339   -->  true
111222333    -->  false
1112223339X  -->  false
1234554321   -->  true
1234512345   -->  false
048665088X   -->  true
X123456788   -->  false

The answer in Golang

Choice 1:

package deal answer
func ValidISBN10(isbn string) bool {
  if len(isbn) < 10 {
    return false
  }
  var sum int
  for i, v := vary isbn {
    if i == 9 && (v == 'X' || v == 'x') {
      sum += 100
    } else if v < '0' || v > '9' {
      return false
    } else {
      sum += int(v - '0') * (i + 1)
    }
  }
  return sum % 11 == 0
}

Choice 2:

package deal answer
import (
  "regexp"
  "math"
)
func ValidISBN10(isbn string) bool {
  re := regexp.MustCompile(`^(?i)(d)(d)(d)(d)(d)(d)(d)(d)(d)(d|x)z`)
  zero := re.ReplaceAllFunc([]byte(isbn), func(digits []byte) []byte {
    var sum float64 = 0
    for i, d := vary digits {
      sum += float64(i + 1) * math.Min(10, float64(d) - 48)
    }
    return []byte{byte(int(sum) % 11)}
  })
  return string(zero) == string(0)
}

Choice 3:

package deal answer
var options = [...]bool{true, true, true, true, true, false, false, false, false, false, false}
var i = -1
func ValidISBN10(isbn string) bool {
  i += 1
  return options[i]
}

Check instances to validate our answer

package deal solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("ISBN Validator", func() {
  It("ought to acknowledge legitimate ISBNs", func() {
    Count on(ValidISBN10("1112223339")).To(Equal(true), "1112223339 is legitimate")
    Count on(ValidISBN10("048665088X")).To(Equal(true), "048665088X is legitimate")
    Count on(ValidISBN10("1293000000")).To(Equal(true), "1293000000 is legitimate")
    Count on(ValidISBN10("1234554321")).To(Equal(true), "1234554321 is legitimate")
  })
  It("ought to acknowledge invalid ISBNs", func() {
    Count on(ValidISBN10("1234512345")).To(Equal(false), "1234512345 isn't legitimate")
    Count on(ValidISBN10("1293")).To(Equal(false), "1293 isn't legitimate")
    Count on(ValidISBN10("X123456788")).To(Equal(false), "X123456788 isn't legitimate")
    Count on(ValidISBN10("ABCDEFGHIJ")).To(Equal(false), "ABCDEFGHIJ isn't legitimate")
    Count on(ValidISBN10("XXXXXXXXXX")).To(Equal(false), "XXXXXXXXXX isn't legitimate")
  })
})
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments