aoc2024/day-17/internal/one/util.go

50 lines
983 B
Go
Raw Normal View History

2024-12-18 15:02:35 +00:00
package one
import (
"bufio"
"io"
"regexp"
"strconv"
"strings"
)
var (
reRegister = regexp.MustCompile(`Register (?P<identifier>[A-Z]): (?P<value>[0-9]+)`)
reProgram = regexp.MustCompile(`Program: (?P<instructions>[0-9,]+)`)
)
func parseLines(r io.Reader) (map[string]int, []int, error) {
registers := make(map[string]int)
var instructions []int
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
switch line := line; {
case reRegister.MatchString(line):
m := reRegister.FindStringSubmatch(line)
registers[m[1]] = mustConv(m[2])
case reProgram.MatchString(line):
m := reProgram.FindStringSubmatch(line)
for _, n := range strings.Split(m[1], ",") {
instructions = append(instructions, mustConv(n))
}
}
}
if err := scanner.Err(); err != nil {
return nil, nil, err
}
return registers, instructions, nil
}
func mustConv(s string) int {
n, err := strconv.Atoi(s)
if err != nil {
panic(err)
}
return n
}