adventofcode/2024/day07/main.go

95 lines
1.5 KiB
Go

package main
import (
"fmt"
"strconv"
"strings"
helpers "git.bullercodeworks.com/brian/adventofcode/helpers"
)
func main() {
inp := helpers.StdinToStringSlice()
part1(inp)
fmt.Println()
part2(inp)
}
func part1(inp []string) {
var total int
for i := range inp {
r, pts := parse(inp[i])
subs := []int{pts[0]}
for _, o := range pts[1:] {
var nxSubs []int
for _, s := range subs {
nxSubs = append(nxSubs, s+o)
if s == 0 {
s = 1
}
nxSubs = append(nxSubs, s*o)
}
subs = nxSubs
}
for _, s := range subs {
if s == r {
total += s
break
}
}
}
fmt.Println("# Part 1")
fmt.Println(total)
}
func part2(inp []string) {
var total int
for i := range inp {
r, pts := parse(inp[i])
subs := []int{pts[0]}
for _, o := range pts[1:] {
var nxSubs []int
for _, s := range subs {
nxSubs = append(nxSubs, s+o)
if s == 0 {
s = 1
}
nxSubs = append(nxSubs, s*o)
ni, _ := strconv.Atoi(fmt.Sprintf("%d%d", s, o))
nxSubs = append(nxSubs, ni)
}
subs = nxSubs
}
for _, s := range subs {
if s == r {
total += s
break
}
}
}
fmt.Println("# Part 2")
fmt.Println(total)
}
func parse(inp string) (int, []int) {
var res int
var rem string
var pts []int
var err error
ptsStr := strings.Split(inp, ":")
if res, err = strconv.Atoi(ptsStr[0]); err != nil {
panic(err)
}
rem = ptsStr[1]
ptsStr = strings.Split(rem, " ")
for _, s := range ptsStr {
p, err := strconv.Atoi(s)
if err != nil {
continue
}
pts = append(pts, p)
}
return res, pts
}