2020 Day 9 Complete

This commit is contained in:
Brian Buller 2020-12-09 07:28:33 -06:00
parent 4756605dfc
commit f1bd9923cb
4 changed files with 1109 additions and 1 deletions

View File

@ -8,7 +8,7 @@ import (
)
func main() {
fmt.Println("# Day 7")
fmt.Println("# Day 8")
inp := h.StdinToStringSlice()
FixProg(inp)
}

1000
2020/day09/input Normal file

File diff suppressed because it is too large Load Diff

88
2020/day09/main.go Normal file
View File

@ -0,0 +1,88 @@
package main
import (
"errors"
"fmt"
h "git.bullercodeworks.com/brian/adventofcode/helpers"
)
func main() {
fmt.Println("# Day 9")
inp := h.StdinToIntSlice()
rogue, err := FindRogueNumber(inp)
if err != nil {
fmt.Println(err.Error())
return
}
answer, err := FindWeakness(rogue, inp)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println("Answer:", answer)
}
func FindRogueNumber(inp []int) (int, error) {
for k, v := range inp {
if k >= 25 {
if !ContainsPairFor(v, inp[k-25:k]) {
return v, nil
}
}
}
return -1, errors.New("All numbers fit")
}
func ContainsPairFor(target int, inp []int) bool {
for i := 0; i < len(inp)-1; i++ {
for k := i + 1; k < len(inp); k++ {
if inp[i]+inp[k] == target {
return true
}
}
}
return false
}
func FindWeakness(target int, inp []int) (int, error) {
for i := 0; i < len(inp)-1; i++ {
for k := i + 1; k < len(inp); k++ {
sum := GetSumForRange(inp[i:k])
if sum == target {
return FindSmallest(inp[i:k]) + FindLargest(inp[i:k]), nil
} else if sum > target {
break
}
}
}
return -1, errors.New("No weakness found")
}
func GetSumForRange(inp []int) int {
var ret int
for k := range inp {
ret = ret + inp[k]
}
return ret
}
func FindSmallest(inp []int) int {
ret := inp[0]
for k := range inp {
if inp[k] < ret {
ret = inp[k]
}
}
return ret
}
func FindLargest(inp []int) int {
ret := inp[0]
for k := range inp {
if inp[k] > ret {
ret = inp[k]
}
}
return ret
}

20
2020/day09/testinput Normal file
View File

@ -0,0 +1,20 @@
35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576