aoc/2024/day-07/main.go
2024-12-07 14:33:17 +01:00

121 lines
2.4 KiB
Go

package main
import (
"bufio"
"fmt"
"log"
"os"
"slices"
"strconv"
"strings"
)
func main() {
file, err := os.Open("./input.txt")
if err != nil {
log.Fatalf("failed to open file: %s\n", err)
}
defer file.Close()
s := bufio.NewScanner(file)
result1 := 0
for s.Scan() {
numsString := strings.Split(s.Text(), " ")
var nums []int
var ans int
for i, s := range numsString {
if i == 0 {
n := strings.Split(s, ":")[0]
ans, err = strconv.Atoi(n)
if err != nil {
log.Fatal(err)
}
continue
}
num, err := strconv.Atoi(s)
if err != nil {
log.Fatal(err)
}
nums = append(nums, num)
}
var currEq []rune = make([]rune, 0)
valid := false
testSolution(&valid, ans, nums, currEq)
if valid {
result1 += ans
}
}
fmt.Println("result part1: ", result1)
}
func testSolution(result *bool, answer int, numbers []int, currentEquasion []rune) {
// fmt.Println(numbers, string(currentEquasion))
if len(currentEquasion) == len(numbers)-1 {
localEq := make([]rune, len(currentEquasion))
copy(localEq, currentEquasion)
localNums := make([]int, len(numbers))
copy(localNums, numbers)
res := localNums[0]
for i := 0; i < len(localNums)-1; i++ {
op := localEq[i]
newNum := localNums[i]
var err error
switch op {
case '|':
{
newNum, err = strconv.Atoi(fmt.Sprint(localNums[i]) + fmt.Sprint(localNums[i+1]))
}
case '*':
{
newNum *= localNums[i+1]
}
case '+':
{
newNum += localNums[i+1]
}
}
if err != nil {
log.Fatal(err)
}
localNums[i] = newNum
localNums = slices.Delete(localNums, i+1, i+2)
localEq = slices.Delete(localEq, i, i+1)
i--
if i < 0 {
res = newNum
}
}
if res == answer {
*result = true
}
return
}
newEquasionMultiply := make([]rune, len(currentEquasion))
copy(newEquasionMultiply, currentEquasion)
newEquasionMultiply = append(newEquasionMultiply, '*')
testSolution(result, answer, numbers, newEquasionMultiply)
newEquasionAdd := make([]rune, len(currentEquasion))
copy(newEquasionAdd, currentEquasion)
newEquasionAdd = append(newEquasionAdd, '+')
testSolution(result, answer, numbers, newEquasionAdd)
newEquasionMerge := make([]rune, len(currentEquasion))
copy(newEquasionMerge, currentEquasion)
newEquasionMerge = append(newEquasionMerge, '|')
testSolution(result, answer, numbers, newEquasionMerge)
}