added comments and improve readability

This commit is contained in:
2023-12-01 22:00:59 +01:00
parent 8e5f071f49
commit fc04fe176e

41
main.go
View File

@@ -38,35 +38,48 @@ func main() {
continue
}
var fLine, lLine string
// forward-scan for spelled digits
var forwardReplacedLine, backwardReplacedLine string
for i := 0; i < len(line); i++ {
fLine += string(line[i])
for k, v := range reMap {
fLine = strings.ReplaceAll(fLine, k, v)
forwardReplacedLine += string(line[i])
// replace found digit by its non-word counterpart (e.g. "one" -> "1")
for key, val := range reMap {
forwardReplacedLine = strings.ReplaceAll(forwardReplacedLine, key, val)
}
}
fmt.Println(fLine)
fmt.Println(forwardReplacedLine)
// backward-scan for spelled digits
for i := len(line) - 1; i >= 0; i-- {
if i == len(line)-1 {
lLine = string(line[i])
backwardReplacedLine = string(line[i])
} else {
lLine = string(line[i]) + lLine
backwardReplacedLine = string(line[i]) + backwardReplacedLine
}
for k, v := range reMap {
lLine = strings.ReplaceAll(lLine, k, v)
// replace found digit by its non-word counterpart (e.g. "one" -> "1")
for key, val := range reMap {
backwardReplacedLine = strings.ReplaceAll(backwardReplacedLine, key, val)
}
}
fmt.Println(lLine)
fmt.Println(backwardReplacedLine)
fMatch := nRegex.FindAllStringSubmatch(fLine, -1)
lMatch := nRegex.FindAllStringSubmatch(lLine, -1)
first := fMatch[0][0]
last := lMatch[len(lMatch)-1:][0][0]
// find single digits in forward-replaced line
firstMatch := nRegex.FindAllStringSubmatch(forwardReplacedLine, -1)
// find single digits in backward-replaced line
lastMatch := nRegex.FindAllStringSubmatch(backwardReplacedLine, -1)
// get first matchgroup, first match (aka first digit in forwardReplacedLine)
first := firstMatch[0][0]
// get last matchgroup, first match (aka last digit in forwardReplacedLine)
last := lastMatch[len(lastMatch)-1:][0][0]
fmt.Println(first + last)
// concatenate digits and convert the resulting string to int
asInt, err := strconv.Atoi(first + last)
if err != nil {
panic(err)