AOC2022/day21/day21.go

87 lines
1.9 KiB
Go
Raw Normal View History

2022-12-21 18:37:32 +01:00
package main
import (
"AOC2022/helper"
"fmt"
"strconv"
"strings"
)
type Operation struct {
value int
apes [2]string
operator string
hasValue bool
}
func main() {
//args := os.Args[1:]
lines := helper.ReadTextFile("day21/input")
apes := make(map[string]Operation)
apesWithValue := []string{}
apesWithOutValue := []string{}
for _, line := range lines {
id, operation := getApe(line)
apes[id] = operation
if len(operation.operator) > 0 {
apesWithOutValue = append(apesWithOutValue, id)
} else {
apesWithValue = append(apesWithValue, id)
}
}
fmt.Println(apesWithValue)
fmt.Println(apesWithOutValue)
for len(apesWithOutValue) > 0 {
apesWithOutValue = step(apesWithOutValue, &apes)
}
fmt.Print(apes["root"])
}
func step(apesWithOutValue []string, apes *map[string]Operation) []string {
newApesWithoutValue := []string{}
for _, id := range apesWithOutValue {
ape := (*apes)[id]
ape1 := (*apes)[ape.apes[0]]
ape2 := (*apes)[ape.apes[1]]
if ape1.hasValue && ape2.hasValue {
ape.value = calcOperation(ape1.value, ape2.value, ape.operator)
ape.hasValue = true
(*apes)[id] = ape
} else {
newApesWithoutValue = append(newApesWithoutValue, id)
}
}
return newApesWithoutValue
}
func getApe(line string) (id string, operation Operation) {
splitLine := strings.Split(line, ": ")
id = splitLine[0]
if strings.ContainsAny(splitLine[1], " ") {
operationLine := strings.Split(splitLine[1], " ")
operation.apes[0] = operationLine[0]
operation.apes[1] = operationLine[2]
operation.operator = string(operationLine[1][0])
} else {
operation.hasValue = true
operation.value = helper.RemoveError(strconv.Atoi(splitLine[1]))
}
return
}
func calcOperation(val1, val2 int, op string) int {
switch op {
case "*":
return val1 * val2
case "/":
return val1 / val2
case "+":
return val1 + val2
case "-":
return val1 - val2
default:
return -99999999999999
}
}