From a16d3c95b854437d22feb2f026d8be7d4643cf44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Borna=20Rajkovi=C4=87?= Date: Sun, 8 Dec 2024 17:00:28 +0100 Subject: [PATCH] Day 07. part 2 --- day_07/solution.go | 54 +++++++++++++++++++++++++++++++++++------ day_07/solution_test.go | 18 +++++++------- 2 files changed, 55 insertions(+), 17 deletions(-) diff --git a/day_07/solution.go b/day_07/solution.go index 02ff3d4..fd24d87 100644 --- a/day_07/solution.go +++ b/day_07/solution.go @@ -1,10 +1,19 @@ package day_07 import ( + "math" "strconv" "strings" ) +type Operator int + +const ( + ADD = iota + MULTIPLY = iota + CONCAT = iota +) + type Equation struct { Result int Variables []int @@ -16,40 +25,69 @@ func SolveBasic(input string) int { sum := 0 for _, equation := range equations { - if Solvable(equation) { + if Solvable(equation, 2) { sum += equation.Result } } return sum } -func Solvable(equation Equation) bool { - for i := 0; i < 1<<(len(equation.Variables)-1); i++ { - if solvable(equation, i) { +func Solvable(equation Equation, operators int) bool { + for i := 0; i < numberOfSolutions(equation, operators); i++ { + if solvable(equation, operators, i) { return true } } return false } -func solvable(equation Equation, options int) bool { +func numberOfSolutions(equation Equation, operators int) int { + return int(math.Pow(float64(operators), float64(len(equation.Variables)-1))) +} + +func solvable(equation Equation, operators int, options int) bool { sum := equation.Variables[0] + for i := 0; i < len(equation.Variables)-1; i++ { if sum > equation.Result { return false } - if options&(1<= larger { + larger *= 10 + } + return larger +} + // task:https://adventofcode.com/2024/day/7#part2 func SolveComplex(input string) int { - return 0 + equations := loadEquations(input) + + sum := 0 + for _, equation := range equations { + if Solvable(equation, 3) { + sum += equation.Result + } + } + return sum } func loadEquations(input string) (equations []Equation) { diff --git a/day_07/solution_test.go b/day_07/solution_test.go index 2c48b1b..58ba45b 100644 --- a/day_07/solution_test.go +++ b/day_07/solution_test.go @@ -18,17 +18,17 @@ func TestBasicSolutionExample(t *testing.T) { func TestComplexSolutionExample(t *testing.T) { result := day_07.SolveComplex(ExampleData) - if result != 6 { - t.Fatalf("Expected 6 received %d", result) + if result != 11387 { + t.Fatalf("Expected 11387 received %d", result) } } -func TestSolvableExample(t *testing.T) { - result := day_07.Solvable(day_07.Equation{ - Result: 45694842, - Variables: []int{2, 9, 227, 6, 1, 5, 4, 382, 1, 5, 2}, - }) - if !result { - t.Fatalf("Expected true received false") +func TestSolvable(t *testing.T) { + if !day_07.Solvable(day_07.Equation{ + Result: 27100, + Variables: []int{3, 9, 100}, + }, 3) { + t.Fatalf("Expected true") } + }