added 03/01
This commit is contained in:
64
03/main.go
Normal file
64
03/main.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
inputFile = flag.String("input", "input.txt", "input filename")
|
||||
digRegex = regexp.MustCompile(`(?m)\d+`)
|
||||
)
|
||||
|
||||
func NearSymbols(line string, lineLen int, pos []int) (symbols int) {
|
||||
// fmt.Printf("looking at %s, line-length=%d\n", line[pos[0]:pos[1]], lineLen)
|
||||
for i := pos[0] + lineLen - 1; i < (pos[1] + lineLen + 1); i++ {
|
||||
if i < 0 || i >= len(line) {
|
||||
// fmt.Printf("skipped invalid index %d (len=%d)\n", i, len(line))
|
||||
continue
|
||||
}
|
||||
|
||||
// fmt.Println("looking at " + string(line[i]))
|
||||
|
||||
if line[i] != '.' && line[i] != '\n' && (line[i] < 48 || line[i] > 57) {
|
||||
fmt.Printf("found %s\n", string(line[i]))
|
||||
symbols++
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
input, err := os.ReadFile(*inputFile)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
var sum int
|
||||
strIn := string(input)
|
||||
lineLen := strings.Index(strIn, "\n") + 1
|
||||
allNumbers := digRegex.FindAllStringIndex(strIn, -1)
|
||||
|
||||
for _, numMatch := range allNumbers {
|
||||
symbols := 0
|
||||
symbols += NearSymbols(strIn, lineLen*-1, numMatch)
|
||||
symbols += NearSymbols(strIn, 0, numMatch)
|
||||
symbols += NearSymbols(strIn, lineLen, numMatch)
|
||||
|
||||
if symbols > 0 {
|
||||
numberAsInt, err := strconv.Atoi(strIn[numMatch[0]:numMatch[1]])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
sum += numberAsInt
|
||||
fmt.Printf("%d matched with %d symbols\n", numberAsInt, symbols)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("sum: %d\n", sum)
|
||||
}
|
Reference in New Issue
Block a user