107 lines
2.3 KiB
Go
107 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"AoC2020/helper"
|
|
"fmt"
|
|
"os"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
func main() {
|
|
args := os.Args[1:]
|
|
input, err := helper.GetInput(args[0])
|
|
var results []int
|
|
var resultsPart2 []int
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
}
|
|
for _, val := range input{
|
|
results = append(results,calculateFormel(val,calculateFormelPart))
|
|
resultsPart2 = append(resultsPart2,calculateFormel(val,calculateFormelPartPart2))
|
|
}
|
|
sum := 0
|
|
sumPart2 := 0
|
|
for _, val := range results{
|
|
sum += val
|
|
}
|
|
for _, val := range resultsPart2{
|
|
sumPart2 += val
|
|
}
|
|
fmt.Println(sum)
|
|
fmt.Println(sumPart2)
|
|
}
|
|
|
|
func calculateFormel(formel string, formelPartFunc func(formel string) int) int{
|
|
cleanFormel := strings.ReplaceAll(formel," ","")
|
|
var formelParts []string
|
|
result := 0
|
|
for result == 0 {
|
|
r, _ := regexp.Compile("\\([0-9+\\-*]*\\)")
|
|
formelParts = r.FindAllString(cleanFormel, -1)
|
|
if len(formelParts) > 0 {
|
|
for _, part := range formelParts {
|
|
result := strconv.Itoa(formelPartFunc(part))
|
|
cleanFormel = strings.Replace(cleanFormel,part,result,-1)
|
|
}
|
|
}else {
|
|
result = formelPartFunc(cleanFormel)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func calculateFormelPart (formel string) int{
|
|
cleanFormel := strings.ReplaceAll(formel,"(","")
|
|
cleanFormel = strings.ReplaceAll(cleanFormel,")","")
|
|
r, _ := regexp.Compile("[ +*\\-]?[0-9]*")
|
|
formelParts := r.FindAllString(cleanFormel, -1)
|
|
sum, _ := strconv.Atoi(formelParts[0])
|
|
for i:= 1; i< len(formelParts); i++{
|
|
number, _ := strconv.Atoi(formelParts[i][1:])
|
|
if formelParts[i][0] == '+' {
|
|
sum += number
|
|
}
|
|
if formelParts[i][0] == '-' {
|
|
sum -= number
|
|
}
|
|
if formelParts[i][0] == '*' {
|
|
sum *= number
|
|
}
|
|
}
|
|
return sum
|
|
}
|
|
|
|
func calculateFormelPartPart2 (formel string) int{
|
|
cleanFormel := strings.ReplaceAll(formel,"(","")
|
|
cleanFormel = strings.ReplaceAll(cleanFormel,")","")
|
|
formelParts := strings.Split(cleanFormel,"*")
|
|
var formelPartsSum []int
|
|
for _, part := range formelParts {
|
|
formelPartsSum = append(formelPartsSum,calculateFormelPart(part))
|
|
}
|
|
product := 1
|
|
for _, multiplier := range formelPartsSum {
|
|
product *= multiplier
|
|
}
|
|
return product
|
|
}
|
|
|
|
|
|
func sortOperation(a,b int) bool {
|
|
return true
|
|
}
|
|
|
|
func sortOperationsPart2(a,b string) bool {
|
|
if a[0] == '+' | '-' {
|
|
return true
|
|
}else{
|
|
return false
|
|
}
|
|
}
|
|
|
|
func split(r rune) bool{
|
|
return r == '(' || r== ')'
|
|
}
|