aoc2023/day-1/one.go

28 lines
558 B
Go
Raw Normal View History

2023-12-02 15:07:04 +00:00
package main
import (
"fmt"
"regexp"
"strconv"
)
// one takes a string array and for each line:
// Combine the first digit and the last digit (in that order) to form a single two-digit number.
// Returns the sum of all calibrated values.
func one(lines []string) (int, error) {
re := regexp.MustCompile(`\d`)
sum := 0
for _, line := range lines {
m := re.FindAllString(line, -1)
if len(m) > 0 {
num, err := strconv.Atoi(fmt.Sprintf("%s%s", m[0], m[len(m)-1]))
if err != nil {
return 0, err
}
sum += num
}
}
return sum, nil
}