add aoc 2025 day 2 solution

This commit is contained in:
Nico 2025-12-02 22:42:06 +11:00
parent 2910d6313c
commit 40fd202244
Signed by: nico
SSH key fingerprint: SHA256:XuacYOrGqRxC3jVFjfLROn1CSvLz85Dec6N7O9Gwu/0
3 changed files with 84 additions and 0 deletions

75
2025/2/main.go Normal file
View file

@ -0,0 +1,75 @@
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
}