aoc/2025/2/main.go
2025-12-02 22:42:06 +11:00

75 lines
1.5 KiB
Go

package main
import (
"fmt"
"os"
"regexp"
"strconv"
"strings"
)
type Range struct {
From int
To int
}
func main() {
// iterate over all IDs
var invalidsum int = 0
ranges := Decode("input.txt")
for _, i := range ranges {
fmt.Printf("\niterating over range: %d to %d\n", i.From, i.To)
// +1 makes the range inclusive
for x := range i.To-i.From+1 {
// to get the "real" number as we took it away initially
num := x+i.From
// extract half of the number
numstring := strconv.Itoa(num)
mid := len(numstring)/2
// if both halves are the same, it is an invalid number
if numstring[:mid] == numstring[mid:] {
fmt.Printf("found invalid id %d\n", num)
invalidsum = invalidsum + num
}
}
}
fmt.Println("sum of invalid ids:", invalidsum)
}
func Decode(filename string) []Range {
f, err := os.ReadFile(filename)
if err != nil {
panic(err)
}
fstring := string(f)
fromrangeregex := regexp.MustCompile("^[0-9]*")
torangeregex := regexp.MustCompile("[0-9]*$")
var ranges []Range
for _, i := range strings.Split(fstring, ",") {
// get range from IDs to iterate over
fromrangestr := fromrangeregex.FindAllString(i, 1)
torangestr := torangeregex.FindAllString(i, 1)
var a Range
fromrange, _ := strconv.Atoi(fromrangestr[0])
torange, _ := strconv.Atoi(torangestr[0])
a.From = fromrange
a.To = torange
fmt.Printf("\nextracted ranges to iterate over: %d to %d\n", fromrange, torange)
ranges = append(ranges, a)
}
return ranges
}