89 lines
1.5 KiB
Go
89 lines
1.5 KiB
Go
|
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
|
||
|
}
|