checkdigitcalculator/main.go

119 lines
2.5 KiB
Go
Raw Normal View History

2023-12-07 11:34:00 -05:00
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
2023-12-07 11:34:00 -05:00
func main() {
directory, err := os.Getwd()
Error(err)
fmt.Printf("What is the name of the file: ")
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
Error(err)
input = strings.TrimSpace(input)
file, err := os.Open(input)
Error(err)
var upcs []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
upcs = append(upcs, scanner.Text())
}
err = file.Close()
Error(err)
if scanner.Err() != nil {
fmt.Println(scanner.Err())
}
var gtins []string
for _, upc := range upcs {
upcLength := len(upc)
// Check Digit Formula
// Take all the digits in odd positions, add them and multiply by three
// Take all the digits in even positions (except for the last one) and add to the number you got above
// Divide that number by 10 and take the remainder
// If the remainder is not 0, subtract it from 10
2023-12-08 10:46:19 -05:00
//
// 12/8/2023: New git updates from https://www.gs1.org/services/how-calculate-check-digit-manually
oddNumber := 0
evenNumber := 0
var remainder int
2023-12-08 10:46:19 -05:00
if upcLength < 8 {
gtins = append(gtins, "Cannot process upcs less than 8 digits")
continue
}
2023-12-08 10:46:19 -05:00
if upcLength > 17 {
gtins = append(gtins, "Invalid barcode")
continue
}
2023-12-08 10:46:19 -05:00
if upcLength%2 == 0 {
for i, num := range upc {
if i%2 != 0 {
convertedOddNumber, err := strconv.Atoi(string(num))
Error(err)
convertedOddNumber = convertedOddNumber * 3
oddNumber += convertedOddNumber
} else {
if upcLength-1 > i {
convertedEvenNumber, err := strconv.Atoi(string(num))
Error(err)
evenNumber += convertedEvenNumber
}
}
}
} else {
for i, num := range upc {
if i%2 == 0 {
convertedOddNumber, err := strconv.Atoi(string(num))
Error(err)
2023-12-08 10:46:19 -05:00
convertedOddNumber = convertedOddNumber * 3
oddNumber += convertedOddNumber
} else {
if upcLength-1 > i {
convertedEvenNumber, err := strconv.Atoi(string(num))
Error(err)
evenNumber += convertedEvenNumber
}
}
}
}
remainder = (oddNumber + evenNumber) % 10
if remainder != 0 {
remainder = 10 - remainder
}
remainderString := strconv.Itoa(remainder)
gtins = append(gtins, upc+remainderString)
}
if _, err := os.Stat(directory + "/answer.txt"); err == nil {
e := os.Remove(directory + "/answer.txt")
Error(e)
}
answerFile, err := os.Create(directory + "/answer.txt")
Error(err)
defer answerFile.Close()
for _, gtin := range gtins {
_, err := answerFile.WriteString(gtin + "\n")
Error(err)
}
2023-12-07 11:34:00 -05:00
}